<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
ini_set('max_execution_time', '0');

/*******************
***  自动匹配物流信息
***  http://192.168.1.100:89/fshop/
*** 2017/06/03
**********/
class Orderexpress
{

	 public function __construct()
    {
        $this->CI =& get_instance();
		$this->db = $this->CI->load->database('default', TRUE);
		$this->CI->load->model('Function_m','fun');
    }
	
	public function getexpressorderlist($ordersn="")
	{	
		$this->db->select('sqlfilter,logisticsID,logistics');
		$this->db->order_by('priority', 'ASC');
		$ordersearchlist = $this->db->get_where("db_order_search",array("status"=>0))->result_array();
		
		foreach($ordersearchlist as $key=>$rs)
		{
			$sql = $rs["sqlfilter"];
			if($ordersn)
			{
				$query = $this->db->query("SELECT order_id,country_cn,country,province,orderweight FROM db_order_list WHERE 1 and order_sn='".trim($ordersn)."'  $sql");
			}else{
				$query = $this->db->query("SELECT order_id,country_cn,country,province,orderweight FROM db_order_list WHERE (shipping_id =0 or shipping_id is NULL)  AND order_status =2  $sql");
			}
			$dates = $query->result_array();
			if(count($dates) >0 )
			{
				foreach($dates as $k=>$res){
					$freight= 0;
					//计算预估运费
					$rsdbexfee = $this->db->get_one("SELECT * FROM db_order_express_formula WHERE expresstypeid = '".$rs["logisticsID"]."'");
					if($rsdbexfee)
					{
						if($res["country"]=='china' || $res["country"]=='中国' || $res["province"]=='北海道' || $res["province"]=='沖縄県')	//如果是中国的快递，使用省份重新计算预估运费
						{
							$country_cn= $res['province'];
						}else{
							$country_cn= $res["country_cn"];
						}
						
						$freight = $this->CI->fun->get_Estimate_freight($res["orderweight"],$country_cn,0,$rs["logistics"]);
						
					}
					//预估运费结束
					$this->db->update("db_order_list",array("shipping_name"=>$rs["logistics"],"shipping_id"=>$rs["logisticsID"],"shipping_expectfee"=>$freight),"order_id ='".$res["order_id"]."'");
				}
			}
			
		}
		echo "OK";
		//print_r($ordersearchlist);
	}

	/*********************
	*** 判断订单状态信息
	*** 只更5天的所有信息
	是否超重 is_overweight = 1 超重 
			 is_overweight = 2 不超重
	
	是否缺货 所有已支付的订单
	********************/
	public function changorderstatus()
	{
		$starttime = strtotime(date("Y-m-d")." 00:00:00");
		$starttime  =  $starttime - (5*86400);
		$endtime   = strtotime(date("Y-m-d")." 23:59:59");
		$query = $this->db->query("SELECT order_id,orderweight FROM db_order_list WHERE is_overweight =0 and add_time>='".$starttime."' AND add_time <='".$endtime."'");
		$dates = $query->result_array();
		foreach($dates as $key=>$rs)
		{
			if($rs["orderweight"] >=2000)
			{
				$this->db->update("db_order_list",array("is_overweight"=>1),"order_id='".$rs["order_id"]."'");	//超重
			}else{
				$this->db->update("db_order_list",array("is_overweight"=>2),"order_id='".$rs["order_id"]."'");	//不超重
			}
		}
	}
	/*********************
	*** 判断订单状态信息
	*** 修改成通过订单号判断是否缺货
	*** 用于订单修改SKU时，即时获取是否缺货标志 
	********************/	
	public function isquehuo($orderid)
	{
			$sql = "SELECT GROUP_CONCAT(goods_id) as goods_id FROM `db_order_sell` WHERE order_id = '".$orderid."'";
			$res = $this->db->get_one($sql);
			if($res["goods_id"])
			{
					$sql = "SELECT GROUP_CONCAT(stock) as stock FROM  db_goods_stock where  goods_id in($res[goods_id]) and storage_id = 1 ";
					$stock = $this->db->get_one($sql);
					$stocklist = explode(",",$stock["stock"]);
					$isque =1;
					foreach($stocklist as $srd)
					{
						if($srd<=0)
						{
							$isque = 0;
							break;
						}

					}
					if($isque==0)
					{
						$this->db->update("db_order_list",array("is_que"=>1),"order_id='".$orderid."'");	//缺货
					}else{
						$this->db->update("db_order_list",array("is_que"=>2),"order_id='".$orderid."'");	//不缺货
					}
			}

	}
	/*********************
	*** 自动将订单从已发货改成已完成
	********************/	
	public function isendorder()
	{
		$query = $this->db->query("SELECT order_id FROM db_order_list WHERE order_status=4");
		$dates = $query->result_array();
		foreach($dates as $key=>$rs)
		{
			$this->db->update("db_order_list",array("order_status"=>5),"order_id='".$rs["order_id"]."'");
			//更新日志表db_goods_log
			$imgdata="";
			$imgdata["content"] = '修改状态为：已完成';
			$imgdata["goods_id"] = $rs['order_id'];	//订单ID db_order_list
			$imgdata["updatetime"] = date("Y-m-d H:i:s");
			$imgdata["createUid"] = 0;
			$imgdata["types"] = 3;
			$imgdata["createUser"] ='auto';
			$this->db->insert('db_goods_log', $imgdata);
		}

	}
	/*********************
	 *** 判断订单状态信息
	 *** 只更180天的所有信息
	是否缺货 所有已支付的订单
	 ********************/
	public function isquehuotest($nowtime,$str_order_ids)
	{
			if(!$nowtime){
				$nowtime = time();
			}
			$sql_exec = "SELECT order_id,order_sn,shopname,country_code,platformID FROM db_order_list WHERE shipping_status = 0 AND order_id in ({$str_order_ids}) ";
			//$sql_exec = "SELECT order_id,order_sn,shopname,country_code,platformID FROM db_order_list WHERE (order_status = 2 or order_status = 1) AND shipping_status = 0 AND add_time <= '{$nowtime}' AND (shipping_number = '' or shipping_number IS NULL) AND order_id in ({$str_order_ids}) ";
			$query = $this->db->query($sql_exec);//默认未分仓  0为未分仓
			//$query = $this->db->query("SELECT order_id,order_sn,shopname,country_code,platformID FROM db_order_list WHERE (order_status = 2 or order_status = 1) AND shipping_status = 0 AND (shipping_number = '' or shipping_number IS NULL) ");//默认未分仓  0为未分仓
			$dates = $query->result_array();

			//获取的店铺必须使用海外仓库发货 德国海外仓
			/**
			$arr_shop_de = explode("\n", $this->CI->config->item('germanyshopname')); //获取所设店铺
			foreach ($arr_shop_de as $k => $v) {
				$arr_shop_de[$k] = trim($v);
			}
			//获取店铺以及sku 目前wish平台下某一个店铺及其sku 发货仓库若存在该sku库存 使用该仓库发货  德国海外仓
			//店铺一 德国仓  wish-Airnin Cloth
			$arr_wish_airnin = explode("|", $this->CI->config->item('germanyshopsku'));
			$wish_airnin = 1; //若为真，则说明已设置相关参数，需要进行判断
			if (count($arr_wish_airnin) == 2) {
				$arr_wish_airnin_name = $arr_wish_airnin[0];
				$arr_wish_airnin_sku = explode(",", $arr_wish_airnin[1]);//店铺下指定发货仓sku
			} else {
				$wish_airnin = 0;
			}
			//店铺二 德国仓  wish-Healthtop
			$arr_wish_healthtop = explode("|", $this->CI->config->item('germanyHealthtop'));
			$wish_healthtop = 1; //若为真，则说明已设置相关参数，需要进行判断
			if (count($arr_wish_healthtop) == 2) {
				$arr_wish_healthtop_name = $arr_wish_healthtop[0];
				$arr_wish_healthtop_sku = explode(",", $arr_wish_healthtop[1]);
			} else {
				$wish_healthtop = 0;
			}
			//店铺三 德国仓 wish-Clarence
			$arr_wish_clarence = explode("|", $this->CI->config->item('germanyClarence'));
			$wish_clarence = 1; //若为真，则说明已设置相关参数，需要进行判断
			if (count($arr_wish_clarence) == 2) {
				$arr_wish_clarence_name = $arr_wish_clarence[0];
				$arr_wish_clarence_sku = explode(",", $arr_wish_clarence[1]);
			} else {
				$wish_clarence = 0;
			}
			//店铺四 德国仓 Wish-ruler
			$arr_wish_ruler = explode("|", $this->CI->config->item('germanyruler'));
			$wish_ruler = 1; //若为真，则说明已设置相关参数，需要进行判断
			if (count($arr_wish_ruler) == 2) {
				$arr_wish_ruler_name = $arr_wish_ruler[0];
				$arr_wish_ruler_sku = explode(",", $arr_wish_ruler[1]);
			} else {
				$wish_ruler = 0;
			}


			//***英国仓发货店铺
			$arr_shop_uk = explode("\n", $this->CI->config->item('ukshopname')); //获取英国所设店铺
			if ($arr_shop_uk) {
				foreach ($arr_shop_uk as $k => $v) {
					$arr_shop_uk[$k] = trim($v);
				}
			}

			//***美国仓发货店铺
			$arr_shop_usa = explode("\n", $this->CI->config->item('usashopname')); //获取美国所设店铺
			if (!empty($arr_shop_usa)) {
				foreach ($arr_shop_usa as $k => $v) {
					$arr_shop_usa[$k] = trim($v);
				}
			}
			//EZGO美国仓发货店铺及SKU
		    //获取店铺以及sku 目前ebay以及速卖通平台下某一个店铺及其sku 发货仓库若存在该sku库存 使用该仓库发货 EZGO美国仓
			//店铺一 EZGO美国仓  ebay-greatitemzone
			$arr_greatitemzone = explode("|", $this->CI->config->item('usagreatitemzone'));
			$ebay_greatitemzone = 1; //若为真，则说明已设置相关参数，需要进行判断
			if (count($arr_greatitemzone) == 2) {
				$arr_greatitemzone_name = $arr_greatitemzone[0];
				$arr_greatitemzone_sku = explode(",", $arr_greatitemzone[1]);//店铺下指定发货仓sku
			} else {
				$ebay_greatitemzone = 0;
			}
			//店铺二 EZGO美国仓  cosplayying
			$arr_cosplayying = explode("|", $this->CI->config->item('usacosplayying'));
			$ebay_cosplayying = 1; //若为真，则说明已设置相关参数，需要进行判断
			if (count($arr_cosplayying) == 2) {
				$arr_cosplayying_name = $arr_cosplayying[0];
				$arr_cosplayying_sku = explode(",", $arr_cosplayying[1]);//店铺下指定发货仓sku
			} else {
				$ebay_cosplayying = 0;
			}
			//店铺三 EZGO美国仓  Ali-costumebuy 速卖通平台
			$arr_costumebuy = explode("|", $this->CI->config->item('usacostumebuy'));
			$aliexpress_costumebuy = 1; //若为真，则说明已设置相关参数，需要进行判断
			if (count($arr_costumebuy) == 2) {
				$arr_costumebuy_name = $arr_costumebuy[0];
				$arr_costumebuy_sku = explode(",", $arr_costumebuy[1]);//店铺下指定发货仓sku
			} else {
				$aliexpress_costumebuy = 0;
			}
			//店铺四 EZGO美国仓  coserlife ebay平台
			$arr_coserlife = explode("|", $this->CI->config->item('usacoserlife'));
			$ebay_coserlife = 1; //若为真，则说明已设置相关参数，需要进行判断
			if (count($arr_coserlife) == 2) {
				$arr_coserlife_name = $arr_coserlife[0];
				$arr_coserlife_sku = explode(",", $arr_coserlife[1]);//店铺下指定发货仓sku
			} else {
				$ebay_coserlife = 0;
			}
			//店铺五 EZGO美国仓  Cosstyle2014 ebay平台
			$arr_Cosstyle2014 = explode("|", $this->CI->config->item('usaCosstyle2014'));
			$ebay_Cosstyle2014 = 1; //若为真，则说明已设置相关参数，需要进行判断
			if (count($arr_costumebuy) == 2) {
				$arr_Cosstyle2014_name = $arr_Cosstyle2014[0];
				$arr_Cosstyle2014_sku = explode(",", $arr_Cosstyle2014[1]);//店铺下指定发货仓sku
			} else {
				$ebay_Cosstyle2014 = 0;
			} **/

			//正文 、订单池循环
			$isto = 0;
			foreach ($dates as $key => $rs) {
				//$rs['order_id'] = 19850; //测试
				$sql = "SELECT GROUP_CONCAT(goods_id) as goods_id,GROUP_CONCAT(goods_sn) as goods_sku,GROUP_CONCAT(goods_number) as goods_number FROM `db_order_sell` WHERE order_id = '" . $rs["order_id"] . "'";
				$res = $this->db->get_one($sql);
				if ($res["goods_id"]) {  //上文已过滤 待审查订单
					//通用订单数据
					$sql_order_list = "SELECT * FROM `db_order_list` WHERE order_id = '" . $rs["order_id"] . "'";
					$rs_order_list = $this->db->query($sql_order_list)->row_array();
					//商品信息
					$sql_order_sell = "SELECT * FROM db_order_sell a LEFT JOIN db_goods_stock b ON a.goods_id = b.goods_id WHERE a.order_id = '" . $rs["order_id"] . "'"." GROUP BY a.rec_id ";
					$goodslist = $this->db->query($sql_order_sell)->result_array();
					//英国仓发货店铺
					/**
					if (in_array(trim($rs['shopname']), $arr_shop_uk)) {
						//指定发货仓库为英国仓
						$res_arr = $this->doSendGoodsByUkWarehouse($rs_order_list, $goodslist);
						continue;
					}**/

					//EZGO美国仓发货 店铺
					/**
					if (in_array(trim($rs['shopname']), $arr_shop_usa)) {
						//指定发货仓库为美国仓
						$res_arr = $this->doSendGoodsByUsaWarehouse($rs_order_list, $goodslist);
						continue;
					}**/
					//EZGO美国仓指定店铺sku美国仓发货 店铺与sku
					/**
					if($rs['country_code'] == "US"){
						//判断EZGO美国海外仓库存是否存在，存在则海外仓可以发货
						$isque = $this->getStocksCounts($res['goods_sku'], 2, $res['goods_number']);
						//若为0，说明库存不存在，则一号仓发货
						if($isque==0){
							$this->que($res["goods_id"],$rs["order_id"]);
							continue;
						}
						// 1)、店铺一 美国仓  ebay-greatitemzone
						if (trim($rs['shopname']) == $arr_greatitemzone_name&&$ebay_greatitemzone) {        //存在该店铺配置
							$sku_exist = 0;
							foreach ($goodslist as $key => $value) {
								if (!in_array($value['goods_sn'], $arr_greatitemzone_sku)) {
									$sku_exist = 1;
									//$this->que($res["goods_id"],$rs["order_id"]);
									break;
								}
							}
							if (trim($rs['shopname']) == $arr_greatitemzone_name && $sku_exist == 0) {
								//美国仓发货
								$res_arr = $this->doSendGoodsByUsaWarehouse($rs_order_list, $goodslist);
								continue;
							}
						}
						// 2)、店铺二 美国仓  cosplayying
						if (trim($rs['shopname']) == $arr_cosplayying_name&&$ebay_cosplayying) {        //存在该店铺配置
							$sku_exist = 0;
							foreach ($goodslist as $key => $value) {
								if (!in_array($value['goods_sn'], $arr_cosplayying_sku)) {
									$sku_exist = 1;
									//$this->que($res["goods_id"],$rs["order_id"]);
									break;
								}
							}
							if (trim($rs['shopname']) == $arr_cosplayying_name && $sku_exist == 0) {
								//美国仓发货
								$res_arr = $this->doSendGoodsByUsaWarehouse($rs_order_list, $goodslist);
								continue;
							}
						}
						// 3)、店铺三 美国仓  Ali-costumebuy
						if (trim($rs['shopname']) == $arr_costumebuy_name&&$aliexpress_costumebuy) {        //存在该店铺配置
							$sku_exist = 0;
							foreach ($goodslist as $key => $value) {
								if (!in_array($value['goods_sn'], $arr_costumebuy_sku)) {
									$sku_exist = 1;
									//$this->que($res["goods_id"],$rs["order_id"]);
									break;
								}
							}
							if (trim($rs['shopname']) == $arr_costumebuy_name && $sku_exist == 0) {
								//美国仓发货
								$res_arr = $this->doSendGoodsByUsaWarehouse($rs_order_list, $goodslist);
								continue;
							}
						}
						// 4)、店铺四 美国仓  coserlife
						if (trim($rs['shopname']) == $arr_coserlife_name&&$ebay_coserlife) {        //存在该店铺配置
							$sku_exist = 0;
							foreach ($goodslist as $key => $value) {
								if (!in_array($value['goods_sn'], $arr_coserlife_sku)) {
									$sku_exist = 1;
									//$this->que($res["goods_id"],$rs["order_id"]);
									break;
								}
							}
							if (trim($rs['shopname']) == $arr_coserlife_name && $sku_exist == 0) {
								//美国仓发货
								$res_arr = $this->doSendGoodsByUsaWarehouse($rs_order_list, $goodslist);
								continue;
							}
						}
						// 5)、店铺五 美国仓  Cosstyle2014
						if (trim($rs['shopname']) == $arr_Cosstyle2014_name&&$ebay_Cosstyle2014) {        //存在该店铺配置
							$sku_exist = 0;
							foreach ($goodslist as $key => $value) {
								if (!in_array($value['goods_sn'], $arr_Cosstyle2014_sku)) {
									$sku_exist = 1;
									//$this->que($res["goods_id"],$rs["order_id"]);
									break;
								}
							}
							if (trim($rs['shopname']) == $arr_Cosstyle2014_name && $sku_exist == 0) {
								//美国仓发货
								$res_arr = $this->doSendGoodsByUsaWarehouse($rs_order_list, $goodslist);
								continue;
							}
						}

					}**/
					//1.德国海外仓库发货的店铺
					/**
					if (in_array(trim($rs['shopname']), $arr_shop_de)) {
						//指定发货仓库为德国仓
						$res_arr = $this->doSendGoodsByDeWarehouse($rs_order_list, $goodslist);
						continue;
					}
					//2.指定店铺sku德国仓发货 店铺与sku
					if($rs['country_code'] == "DE"){
						//判断德国海外仓库存是否存在，存在则海外仓可以发货
						$isque = $this->getStocksCounts($res['goods_sku'], 0, $res['goods_number']);
						//若为0，说明库存不存在，则一号仓发货
						if($isque==0){
							$this->que($res["goods_id"],$rs["order_id"]);
							continue;
						}
						// 1)、店铺一 德国仓  wish-Airnin Cloth
						if (trim($rs['shopname']) == $arr_wish_airnin_name&&$wish_airnin) {        //存在该店铺配置
								$sku_exist = 0;
								foreach ($goodslist as $key => $value) {
									if (!in_array($value['goods_sn'], $arr_wish_airnin_sku)) {
										$sku_exist = 1;
										//$this->que($res["goods_id"],$rs["order_id"]);
										break;
									}
								}
								if (trim($rs['shopname']) == $arr_wish_airnin_name && $sku_exist == 0) {
									//德国仓发货
									$res_arr = $this->doSendGoodsByDeWarehouse($rs_order_list, $goodslist);
									continue;
								}
						}
						// 2)、店铺二 德国仓  wish-Healthtop
						if (trim($rs['shopname']) == $arr_wish_healthtop_name&&$wish_healthtop) {        //存在该店铺配置
								$sku_exist = 0;
								foreach ($goodslist as $key => $value) {
									if (!in_array($value['goods_sn'], $arr_wish_healthtop_sku)) {
										$sku_exist = 1;
										//$this->que($res["goods_id"],$rs["order_id"]);
										break;
									}
								}
								if (trim($rs['shopname']) == $arr_wish_healthtop_name && $sku_exist == 0) {
									//德国仓发货
									$res_arr = $this->doSendGoodsByDeWarehouse($rs_order_list, $goodslist);
									continue;
								}
						}
						// 3)、店铺三 德国仓  wish-Clarence
						if (trim($rs['shopname']) == $arr_wish_clarence_name&&$wish_clarence) {        //存在该店铺配置
								$sku_exist = 0;
								foreach ($goodslist as $key => $value) {
									if (!in_array($value['goods_sn'], $arr_wish_clarence_sku)) {
										$sku_exist = 1;
										//$this->que($res["goods_id"],$rs["order_id"]);
										break;
									}
								}
								if (trim($rs['shopname']) == $arr_wish_clarence_name && $sku_exist == 0) {
									//德国仓发货
									$res_arr = $this->doSendGoodsByDeWarehouse($rs_order_list, $goodslist);
									continue;
								}
						}
						// 4)、店铺四 德国仓  wish-ruler
						if (trim($rs['shopname']) == $arr_wish_ruler_name&&$wish_ruler) {        //存在该店铺配置
							$sku_exist = 0;
							foreach ($goodslist as $key => $value) {
								if (!in_array($value['goods_sn'], $arr_wish_ruler_sku)) {
									$sku_exist = 1;
									//$this->que($res["goods_id"],$rs["order_id"]);
									break;
								}
							}
							if (trim($rs['shopname']) == $arr_wish_ruler_name && $sku_exist == 0) {
								//德国仓发货
								$res_arr = $this->doSendGoodsByDeWarehouse($rs_order_list, $goodslist);
								continue;
							}
						}

					}**/
					//3.美国仓，如果有货的话，美国仓发货

					//暂停 美国仓不发货 10/8
					/**
					if ($rs['country_code'] == "US") {
						////发往美国的 仓库id 为6
						//$isque = $this->getStocksCounts($res['goods_id'],6); //以后正式环境
						//亚马逊或网站平台  暂停使用

						if($rs['platformID']==2 || $rs['platformID']==14){
						}else{
							$this->que($res["goods_id"],$rs["order_id"]);
							continue;
						}
						//目前临时t_stocks表
						$isque = $this->getStocksCounts($res['goods_sku'], 2, $res['goods_number']);
						//echo $isque;exit;
						if ($isque == 0) //缺货状态下，走一号仓库
						{
							//查看万邑通 美西仓是否有货，有货的话走该渠道
							$queis = $this->getStocksCounts($res['goods_sku'], 3, $res['goods_number']);
							if ($queis == 0) {
							} else {
								$this->doSendGoodsByWinitWarehouse($rs_order_list, $goodslist);
								continue;
							}
							//$this->db->update("db_order_list",array("shipping_status"=>0),"order_id='".$rs["order_id"]."'");	//缺货
						} else {
							$this->doSendGoodsByUsaWarehouse($rs_order_list, $goodslist);
							continue;
						}
					}**/
					//3.英国仓，如果有货的话，英国仓发货 英国 瑞士
					/**
					if ($rs['country_code'] == "GB" || $rs['country_code'] == "CH"||$rs['country_code'] == "UK") {
						////发往美国的 仓库id 为7
						//$isque = $this->getStocksCounts($res['goods_id'],7); //以后正式环境
						//亚马逊或网站平台
						if($rs['platformID']==2 || $rs['platformID']==14){
						}else{
							$this->que($res["goods_id"],$rs["order_id"]);
							continue;
						}
						//目前临时t_stocks表
						$isque = $this->getStocksCounts($res['goods_sku'], 1, $res['goods_number']);
						if ($isque == 0) //缺货状态下，走一号仓库
						{
							//$this->db->update("db_order_list",array("shipping_status"=>0),"order_id='".$rs["order_id"]."'");	//缺货
						} else {
							$this->doSendGoodsByUkWarehouse($rs_order_list, $goodslist);
							continue;
						}
					}**/
					//4.德国仓，如果有货的话，德国仓发货 德国 奥地利
					/**暂停
					if ($rs['country_code'] == "DE" || $rs['country_code'] == "AT") {
						////发往美国的 仓库id 为5
						//$isque = $this->getStocksCounts($res['goods_id'],5);//以后正式仓库使用
						//亚马逊或网站平台
						if($rs['platformID']==2 || $rs['platformID']==14){
						}else{
							$this->que($res["goods_id"],$rs["order_id"]);
							continue;
						}
						//目前临时t_stocks表
						$isque = $this->getStocksCounts($res['goods_sku'], 0, $res['goods_number']);
						//var_dump($isque);exit;
						if ($isque == 0) //缺货状态下，走一号仓库
						{
							//$this->db->update("db_order_list",array("shipping_status"=>0),"order_id='".$rs["order_id"]."'");	//缺货
						} else {
							//德国仓
							$res_arr = $this->doSendGoodsByDeWarehouse($rs_order_list, $goodslist);
							continue;
						}
					}**/
					//5 默认为一号仓发货
					$this->que($res["goods_id"],$rs["order_id"]);

				}else{
					$this->db->update("db_order_list", array("order_status"=>7), "order_id='" . $rs['order_id'] . "'");    //缺货
				}
			}
	}
	//按照规则进行分仓操作
	public function doSeparateWarehouse(){
		//限制订单范围 (已支付)
		$sel_orderlist = "SELECT GROUP_CONCAT(order_id) as order_id FROM db_order_list WHERE (order_status = 2 or order_status = 1)  AND shipping_status = 0 ";
		//$sel_orderlist = "SELECT GROUP_CONCAT(order_id) as order_id FROM db_order_list WHERE (order_status = 2 or order_status = 1) AND shipping_status = 0 AND (shipping_number = '' or shipping_number IS NULL) ";
		$rss_orderlist = $this->db->query($sel_orderlist)->row_array();
		$str_order_ids = $rss_orderlist['order_id'];
		if(!$str_order_ids){
			echo "NO ORDERS !";exit;
		}
		//记录当前派往海外仓订单
		$arr_oversea_orders = array();


		//执行规则
		$sql_rules = "SELECT * FROM db_oversea_rules WHERE status = 0 ORDER BY priority ASC ";
		$rs_rules  = $this->db->query($sql_rules)->result_array();
		foreach($rs_rules as $k=>$v_rule){
			if(!$v_rule['sqlfilter']){
				continue;
			}
			$arr_goodsno = explode(";",$v_rule['goodsno']);
			$goodsnoflag = $v_rule['goodsnoflag'];

			$sql_orderlist = "SELECT * FROM db_order_list WHERE shipping_status = 0 AND order_id in ({$str_order_ids}) ".$v_rule["sqlfilter"];
			//$sql_orderlist = "SELECT * FROM db_order_list WHERE shipping_status = 0 AND (shipping_number = '' or shipping_number IS NULL) AND add_time <= '{$nowtime}' AND order_id in ({$str_order_ids}) ".$v_rule["sqlfilter"];
			$rs_orderlist  = $this->db->query($sql_orderlist)->result_array();

			if(!$rs_orderlist){
				continue;
			}
			//订单列表
			foreach($rs_orderlist as $key=>$v_order){
				//$fields = "a.order_id,a.goods_id,a.goods_sn,b.g_pd_width,g_pd_height,g_pd_length";
				$sql_ordersell = "SELECT * FROM db_order_sell a LEFT JOIN db_goods b ON a.goods_id = b.goods_id WHERE a.order_id = '{$v_order['order_id']}' ";
				$rs_ordersell  = $this->db->query($sql_ordersell)->result_array();


				//商品表 //比对商品长宽高等信息
				$flag = 0; //检测是否需要判断库存
				foreach($rs_ordersell as $kk=>$v_sell){
					//判断sku等信息
					if(!empty($v_rule['goodsno'])){
						if(in_array($v_sell['goods_sn'],$arr_goodsno)){
							if($goodsnoflag==1){
								$flag = 1;
								break;
							}
						}else{
							if($goodsnoflag==1){

							}else{
								$flag = 1;
								break;
							}



						}
					}

					//和值判断
					$sumValue = $v_sell['g_pd_length']+$v_sell['g_pd_width']+$v_sell['g_pd_height'];
					if($v_rule['sumvalue1']&&$sumValue < $v_rule['sumvalue1']){
						$flag = 1;
						break;
					}
					if($v_rule['sumvalue2']&&$sumValue > $v_rule['sumvalue2']){
						$flag = 1;
						break;
					}
					//判断 最长边  次长边  最短边
					$arr_length="";
					$arr_length[] = $v_sell['g_pd_length'];
					$arr_length[] = $v_sell['g_pd_width'];
					$arr_length[] = $v_sell['g_pd_height'];
					@rsort($arr_length);
					//数据表 最长边为 length
					if($v_rule['length1']&&$arr_length[0] < $v_rule['length1']){
						$flag = 1;
						break;
					}
					if($v_rule['length2']&&$arr_length[0] > $v_rule['length2']){
						$flag = 1;
						break;
					}
					//数据表 次长边为 width
					if($v_rule['width1']&&$arr_length[1] < $v_rule['width1']){
						$flag = 1;
						break;
					}
					if($v_rule['width2']&&$arr_length[1] > $v_rule['width2']){
						$flag = 1;
						break;
					}
					//数据表 最短边为 heigth
					if($v_rule['heigth1']&&$arr_length[2] < $v_rule['heigth1']){
						$flag = 1;
						break;
					}
					if($v_rule['heigth2']&&$arr_length[2] > $v_rule['heigth2']){
						$flag = 1;
						break;
					}
					//计算值判断
					$calsValue = $arr_length[0] + ($arr_length[1]+$arr_length[2])*2;
					if($v_rule['calcvalue1']&&$calsValue < $v_rule['calcvalue1']){
						$flag = 1;
						break;
					}
					if($v_rule['calcvalue2']&&$calsValue > $v_rule['calcvalue2']){
						$flag = 1;
						break;
					}

				} //sell foreach


				//检测是否需要判断库存
				if($flag == 0){

					$sql = "SELECT GROUP_CONCAT(goods_id) as goods_id,GROUP_CONCAT(goods_sn) as goods_sku,GROUP_CONCAT(goods_number) as goods_number FROM `db_order_sell` WHERE order_id = '" . $v_order["order_id"] . "'";
					$res = $this->db->get_one($sql);

					$res['goods_sku'] = strtoupper($res['goods_sku']); //全部转换成大写
					//规则里的发货仓库，以及检测是否需要判断库存
					if($v_rule['deliveroversea']==1){ //英华英国仓

						if($v_rule['stockstatus']==2){ //不检测库存是否有货，直接上传
							$arr_oversea_orders[] = $v_order['order_id'];
							$this->doSendGoodsByUkWarehouse($v_order, $rs_ordersell,$v_rule['transportoversea']);
							continue;
						}else{
							//目前临时t_stocks表
							$isque = $this->getStocksCounts($res['goods_sku'], 1, $res['goods_number']);
							if ($isque == 0) //缺货状态下，走一号仓库
							{
								//$this->db->update("db_order_list",array("shipping_status"=>5),"order_id='".$v_order["order_id"]."'");	//缺货
							}else {
								$arr_oversea_orders[] = $v_order['order_id'];
								$this->doSendGoodsByUkWarehouse($v_order, $rs_ordersell,$v_rule['transportoversea']);
								continue;
							}
						}
					}
					if($v_rule['deliveroversea']==2){//英华德国仓


						if($v_rule['stockstatus']==2){
							//德国仓
							$arr_oversea_orders[] = $v_order['order_id'];
							$this->doSendGoodsByDeWarehouse($v_order, $rs_ordersell,$v_rule['transportoversea']);
							continue;
						}else{
							//目前临时t_stocks表
							$isque = $this->getStocksCounts($res['goods_sku'], 0, $res['goods_number']);


							/**
							if($v_sell['order_id']=="227394"&&$v_rule['id']==10){
								$isque = $this->getStocksCounts($res['goods_sku'], 0, $res['goods_number']);
								var_dump($res);exit;
							}**/

							if ($isque == 0) //缺货状态下，走一号仓库
							{
								//$this->db->update("db_order_list",array("shipping_status"=>5),"order_id='".$v_order["order_id"]."'");
							} else {
								//德国仓
								$arr_oversea_orders[] = $v_order['order_id'];
								$this->doSendGoodsByDeWarehouse($v_order, $rs_ordersell,$v_rule['transportoversea']);
								continue;
							}
						}

					}
					if($v_rule['deliveroversea']==3){//EZGO美国仓

						if($v_rule['stockstatus']==2){
							$arr_oversea_orders[] = $v_order['order_id'];
							$this->doSendGoodsByUsaWarehouse($v_order, $rs_ordersell,$v_rule['transportoversea']);
							continue;
						}else{
							//目前临时t_stocks表
							$isque = $this->getStocksCounts($res['goods_sku'], 2, $res['goods_number']);
							if ($isque == 0) //缺货状态下，走一号仓库
							{
								//$this->db->update("db_order_list",array("shipping_status"=>5),"order_id='".$v_order["order_id"]."'");
							} else {
								$arr_oversea_orders[] = $v_order['order_id'];
								$this->doSendGoodsByUsaWarehouse($v_order, $rs_ordersell,$v_rule['transportoversea']);
								continue;
							}
						}

					}
					if($v_rule['deliveroversea']==4){//万邑通美西仓

						if($v_rule['stockstatus']==2){
							$arr_oversea_orders[] = $v_order['order_id'];
							$this->doSendGoodsByWinitWarehouse($v_order,$rs_ordersell,$deliver="1000111");
							continue;
						}else{
							//查看万邑通 美西仓是否有货，有货的话走该渠道
							$queis = $this->getStocksCounts($res['goods_sku'], 3, $res['goods_number']);
							if ($queis == 0) {
							} else {
								$arr_oversea_orders[] = $v_order['order_id'];
								$this->doSendGoodsByWinitWarehouse($v_order,$rs_ordersell,$deliver="1000111");
								continue;
							}
						}
					}
				} //flag 判断

			} //订单  foreach


		}//规则 foreach

		//去掉已经分往海外仓的（可能未成功，留待下次分仓）
		if(count($arr_oversea_orders)>0){
			$orders = implode(",",$arr_oversea_orders);
			$sql_exec = "SELECT order_id,order_sn,shopname,country_code,platformID FROM db_order_list WHERE shipping_status = 0 AND order_id in ({$str_order_ids}) AND order_id not in ({$orders}) ";
		}else{
			$sql_exec = "SELECT order_id,order_sn,shopname,country_code,platformID FROM db_order_list WHERE shipping_status = 0 AND order_id in ({$str_order_ids}) ";
		}

		$query = $this->db->query($sql_exec);//默认未分仓  0为未分仓
		$dates = $query->result_array();
		foreach ($dates as $key => $rs) {
			$sql = "SELECT GROUP_CONCAT(goods_id) as goods_id,GROUP_CONCAT(goods_sn) as goods_sku,GROUP_CONCAT(goods_number) as goods_number FROM `db_order_sell` WHERE order_id = '" . $rs["order_id"] . "'";
			$res = $this->db->get_one($sql);
			if ($res["goods_id"]) {  //上文已过滤 待审查订单
				//判断是否存在 停产商品
				$s = "SELECT * FROM db_goods WHERE goods_id in({$res['goods_id']}) AND g_sale_status = 4 ";
				$r = $this->db->query($s)->row_array();
				if(count($r)>0){
					//有停产商品
					$this->db->update("db_order_list", array("order_status"=>7,"remark"=>"订单包含停售商品"), "order_id='" . $rs['order_id'] . "'");
				}

				//默认为一号仓发货
				$this->que($res["goods_id"],$rs["order_id"]);
			}else{
				$this->db->update("db_order_list", array("order_status"=>7), "order_id='" . $rs['order_id'] . "'");    //缺货
			}
		}
		echo "OK";exit;
		//$this->isquehuotest($nowtime,$str_order_ids);  //注释该函数关于德国仓的一些判断操作等，稍后该函数会注释掉的
		//echo "OK";exit;

	}
	function que($goods_id,$order_id)
	{
		$sql = "SELECT GROUP_CONCAT(stock) as stock FROM  db_goods_stock where  goods_id in($goods_id) and storage_id = 1 ";
		$stock = $this->db->get_one($sql);
		$stocklist = explode(",", $stock["stock"]);
		$isque = 1;
		foreach ($stocklist as $srd) {
			if ($srd <= 0) {
				$isque = 0;
				break;
			}
		}
		if ($isque == 0) {
			$this->db->update("db_order_list", array("is_que" => 1,"shipping_status"=>5), "order_id='" . $order_id . "'");    //缺货
		} else {
			$this->db->update("db_order_list", array("is_que" => 2,"shipping_status"=>5), "order_id='" . $order_id . "'");    //不缺货
		}
		return true;
	}
	//判断库存是否有货 $goodslist 商品列表  $goods_id array    $goods_number array
	private function getStocksCounts($goods_id,$storage_id,$goods_number){
		//目前使用临时海外仓库存表来判断 storage_id  0 德国 1 英国 2 美国,3万邑联（美国） $goods_id 为 goods_sku的逗号分隔
		$arr_sku = explode(",",$goods_id);
		$arr_number = explode(",",$goods_number);
		//获取库存相关信息
		$sql = "SELECT * FROM t_stocks WHERE flag = {$storage_id} ";
		$rs  = $this->db->query($sql)->result_array();
		$arr_stocks_sku = array();
		$arr_stocks_stock = array();
		foreach($rs as $key=>$value){
			$arr_stocks_sku[$key] = $value['Barcode']; //sku编码
			$arr_stocks_stock[$key]=$value['TotalInStock']; //库存数量
		}

		$isque = 1;
		foreach($arr_sku as $k=>$v){
			$ary_stocks_sku = $arr_stocks_sku;
			if(in_array($v,$arr_stocks_sku)){
				$ary_stocks_sku = array_flip($ary_stocks_sku);
				$key = $ary_stocks_sku[$v];
				/**
				if($goods_id=="300920"){
					print_r($arr_stocks_stock[$key]);exit;
					exit;
				}**/
				//判断库存是否足够多
				if($arr_stocks_stock[$key]>=$arr_number[$k]){
				}else{
					$isque = 0;
					break;
				}
			}else{
				$isque = 0;
				break;
			}

		}
		return $isque;
		//正式仓库 db_goods_stock 是代码需修改
		/**
		$sql = "SELECT GROUP_CONCAT(stock) as stock FROM  db_goods_stock where  goods_id in($goods_id) and storage_id = {$storage_id} ";
		$stock = $this->db->get_one($sql);
		$stocklist = explode(",",$stock["stock"]);
		$isque =1;
		foreach($stocklist as $srd)
		{
			if($srd<=0)
			{
				$isque = 0;
				break;
			}
		}
		return $isque;**/
	}
	//英国仓发货
	private function doSendGoodsByUkWarehouse(& $rs_order_list,& $goodslist,$deliver="YH2TK"){
		$url = "https://yinghua.co.uk/Token";
		//$username = "fuman";
		//$password = "Cosplaysky2015";
		$username = $this->CI->config->item('ukusername');
		$password = $this->CI->config->item('ukpass');
		//获取token
		$post_data = array ("username" => $username,"password" => $password,'grant_type'=>'password');
		$post_data = http_build_query($post_data);
		$headers = array("Content-type: Application/x-www-form-urlencoded;charset=utf-8");
		$post_arr_result = $this->sendCurlPostRequest($url,$post_data,$headers);
		$token = $post_arr_result['access_token'];
		//$token="DjoE5osaaiu57qWM1qzvbkM0KvEA0M3RvYAJ_FisDM-JbyIHEm889ZPTl8tSPZfQs8u3P4dEEjmTc4XO6mac4sV_RcQnNH2OSyRk34qYrAjxFQY4SQCVP4rwUO4sp8WVNWQtDFugzC14WkbpIkTdLTziywIY_-9kl-P8kMbXuSOc69yaS51O-lYxdZjcKhnoHo1t_VF-p0537Tvq_JWJc24QSryg2zjmNCbKbLveXgBrEu84dLsUWq0FdcJGJoNbPFBmdhs86501xxU_aAs5l6SmHJ-tduUnrpslBlMT8NAiiSCbtDcLiDo-3RtjOi0XdQOenpFFNMJsb4AL3P0vOQVXCd-DGWFHf9xHSfI5MHOAtyPCq2DekUIyTp_axQV57b4yhAXIp6StcH0T7Zt4cBORzoVcpMEiwhmIwPrYP05AGcZoYVw6aLDtdgFHuUB3dQ2f-mmV_M6f-_YZKOwyDRsm5d8SyaHCBcSxoYqSve6yt5TrxQZzCGz7oGWH6kxx1kH_n05oH3-zTKhcePn1CZCn4uY4_HKA75M0cOWIkIb5Mg0i";
		//echo $token;exit;
		//获取当前可用的邮递服务
		//$stocks_url = "https://yinghua.co.uk/wms/DeliveryServices";
		//$get_arr_result = $this->sendCurlGetRequest($stocks_url,$token);
		//print_r($get_arr_result);exit;
		$arr_order['OrderNumber'] = $rs_order_list['order_sn'];
		//$arr_order['DeliveryServiceCode'] = "YH2TK" ; //测试
		$shipping_name = "";
		$shipping_id = 0;
		/**
		if($rs_order_list['salesOrderId']){  //目前的流程，该项基本用不到，因为第一次提交后已经分仓，所以不会走该判断
			$sql_express = "SELECT * FROM db_order_express WHERE name = '{$rs_order_list['shipping_name']}' ";
			$rs_express = $this->db->query($sql_express)->row_array();
			if(!empty($rs_express['oversea_express'])){
				$shipping_name = $rs_express['name'];
				$shipping_id = $rs_express['id'];
				$arr_order['DeliveryServiceCode'] = $rs_express['oversea_express']; //当为更改后的
			}else{
				//$arr_order['DeliveryServiceCode'] = "YH2TK" ; //默认发货方式
				$arr_order['DeliveryServiceCode'] = $deliver ; //默认发货方式
			}
		}else{
			//$sql_express = "SELECT * FROM db_order_express WHERE oversea_express = 'YH2TK' ";
			$sql_express = "SELECT * FROM db_order_express WHERE oversea_express = '{$deliver}' ";
			$rs_express = $this->db->query($sql_express)->row_array();
			if($rs_express){
				$shipping_id = $rs_express['id'];
				$shipping_name = $rs_express['name'];
			}
			//$arr_order['DeliveryServiceCode'] = "YH2TK" ; //默认发货方式
			$arr_order['DeliveryServiceCode'] = $deliver ; //默认发货方式
		}**/
		$sql_express = "SELECT * FROM db_order_express WHERE oversea_express = '{$deliver}' ";
		$rs_express = $this->db->query($sql_express)->row_array();
		if($rs_express){
			$shipping_id = $rs_express['id'];
			$shipping_name = $rs_express['name'];
		}
		//$arr_order['DeliveryServiceCode'] = "YH2TK" ; //默认发货方式
		$arr_order['DeliveryServiceCode'] = $deliver ; //默认发货方式


		//收件人信息
		$arr_order['Surname'] = $rs_order_list['consignee'];//收货人
		$arr_order['FirstName'] = $rs_order_list['consignee'];
		$address = "";
		if($rs_order_list['address']){
			$address .= $rs_order_list['address'] ; //当为更改后的
		}
		if($rs_order_list['address2']){
			$address .= $rs_order_list['address2'] ;
		}
		if(strlen($address)>35){
			$arr_order['Building'] = substr($address,35);//非必填
			$arr_order['Street'] = substr($address,0,35);
			$arr_order['Area'] = '';//非必填
		}else{
			$arr_order['Building'] = "";//非必填
			$arr_order['Street'] = $address;
			$arr_order['Area'] = '';//非必填
		}

		$arr_order['City'] = $rs_order_list['city'];
		$arr_order['PostCode'] = $rs_order_list['zipcode'];
		$arr_order['Country'] = $rs_order_list['country_code'];
		$arr_order['Phone'] = $rs_order_list['tel'];
		$arr_order['Mobile'] = $rs_order_list['mobile'];
		$arr_order['Email'] = $rs_order_list['paypalmail'];//非必填

		//$post_data['Items'] = ;
		foreach($goodslist as $k_g=>$k_v){
			$arr_order['Items'][$k_g]['Barcode'] = $k_v['goods_sn'];
			$arr_order['Items'][$k_g]['Quantity'] = $k_v['goods_number'];
		}
		$post_order_arr = array($arr_order);
		$order_json = json_encode($post_order_arr);
		$header = array("Authorization: Bearer {$token}","Content-type: Application/json;charset=utf-8");
		//正式请求  若存在则更新，否则上传新订单
		/**
		if($rs_order_list['salesOrderId']){  //目前的流程，该项基本用不到，因为第一次提交后已经分仓，所以不会走该判断
			$json = json_encode($arr_order);
			$stocks_url="https://yinghua.co.uk/wms/Dispatches/{$rs_order_list['salesOrderId']}";
			$res_arr = $this->sendCurlCommonRequest($stocks_url,"put",$json,$header); //更新运输方式等
			$this->db->update("db_order_list",array("shipping_status"=>1,"salesOrderId"=>$rs_order_list['salesOrderId'],"is_nodelivery"=>1,"order_status"=>3,"shipping_name"=>$shipping_name),"order_id='".$rs_order_list["order_id"]."'");
			exit;
		}else{
			$stocks_url = "https://yinghua.co.uk/wms/Dispatches";
			$res_arr = $this->sendCurlPostRequest($stocks_url,$order_json,$header);
		}**/
		$stocks_url = "https://yinghua.co.uk/wms/Dispatches";
		$res_arr = $this->sendCurlPostRequest($stocks_url,$order_json,$header);
		//返回值判断
		if(!empty($res_arr[0])){
			//返回值判断
			$sql_oversea = "SELECT * FROM db_order_oversea WHERE order_id = ".$rs_order_list['order_id'];
			$rs_oversea  = $this->db->query($sql_oversea)->row_array();
			if($res_arr[0]['Status']==200||$res_arr[0]['Status']==204){
				//UserID 客户订单号 客户提供的订单号
				$salesOrderId = $res_arr[0]['SystemID']; //订单对应的发货单号 用于查询是否发货等信息
				if(!empty($rs_oversea)){
					$this->db->update("db_order_oversea",array("salesOrderId"=>$salesOrderId,"isSuccess"=>1),"order_id='".$rs_order_list["order_id"]."'");
				}else{
					$arr_oversea['order_id'] = $rs_order_list['order_id'];
					$arr_oversea['order_sn'] = $rs_order_list['order_sn'];
					$arr_oversea['salesOrderId'] = $salesOrderId;
					$arr_oversea['isSuccess'] = 1;
					$arr_oversea['addTime'] = date("Y-m-d H:i:s");
					$this->db->insert('db_order_oversea',$arr_oversea);
				}
				//更新日志表db_goods_log
				$imgdata["goods_id"] = $rs_order_list['order_id'];	//订单ID db_order_list
				$imgdata["updatetime"] = date("Y-m-d H:i:s");
				$imgdata["createUid"] = 0;
				$imgdata["types"] = 3;
				$imgdata["content"] = '英华英国仓标配货成功,交易ID='.$rs_order_list['order_sn'];
				$imgdata["createUser"] ='auto';
				$this->db->insert('db_goods_log', $imgdata);

				//2代表德国仓 db_order_list shipping_status order_status
				$this->db->update("db_order_list",array("shipping_status"=>1,"salesOrderId"=>$salesOrderId,"is_nodelivery"=>1,"order_status"=>3,"shipping_name"=>$shipping_name,"shipping_id"=>$shipping_id),"order_id='".$rs_order_list["order_id"]."'");
			}else{
				$salesOrderId = $res_arr[0]['SystemID']; //订单对应的发货单号 用于查询是否发货等信息
				$errorMessage = $res_arr[0]['Message']; //错误信息
				if(!empty($rs_oversea)){
					$this->db->update("db_order_oversea",array("salesOrderId"=>$salesOrderId,"errorMessage"=>$errorMessage),"order_id='".$rs_order_list["order_id"]."'");
				}else{
					$arr_oversea['order_id'] = $rs_order_list['order_id'];
					$arr_oversea['order_sn'] = $rs_order_list['order_sn'];
					$arr_oversea['salesOrderId'] = $salesOrderId;
					$arr_oversea['errorMessage'] = $errorMessage;
					//$arr_oversea['isSuccess'] = 0; //默认值为0
					$arr_oversea['addTime'] = date("Y-m-d H:i:s");
					$this->db->insert('db_order_oversea',$arr_oversea);
				}
				//更新日志表db_goods_log
				$imgdata["goods_id"] = $rs_order_list['order_id'];	//订单ID db_order_list
				$imgdata["updatetime"] = date("Y-m-d H:i:s");
				$imgdata["createUid"] = 0;
				$imgdata["types"] = 3;
				$imgdata["content"] = '英华英国仓标配货成功,交易ID='.$rs_order_list['order_sn'].",".$errorMessage;
				$imgdata["createUser"] ='auto';
				$this->db->insert('db_goods_log', $imgdata);

				$this->db->update("db_order_list",array("shipping_status"=>1,"salesOrderId"=>$salesOrderId,"is_nodelivery"=>1,"order_status"=>3,"shipping_name"=>$shipping_name,"shipping_id"=>$shipping_id),"order_id='".$rs_order_list["order_id"]."'");
			}
		}
	}
	//EZGO美国仓发货
	private function doSendGoodsByUsaWarehouse(& $rs_order_list,& $goodslist,$deliver="UPS-G-I"){
		//对接api美国仓 正式环境账号  测试环境账号 已关闭
		$customerId = $this->CI->config->item('goodscode');
		$token = $this->CI->config->item('usatoken');
		$usaSupplierCode = $this->CI->config->item('usasuppliercode');
		$url = "http://openapi.4pis.com:8080/api/service/wmc/order/addSmSalerOrder?token=$token&customerId=$customerId&language=zh_CN&format=json";
		$headers= array("Content-type: Application/json;charset=utf-8");
		$arr_order['custVoucherId'] = $rs_order_list['order_sn']; //客户单证号 必填
		$arr_order['salesModel'] = 1;//销售模式 必填
		$arr_order['customerCorpId'] = "Cosplaysky"; //暂时用这个店铺测试   //店铺编号 必填 $rs_order_list['shopname']
		$arr_order['receiver'] = str_replace("\\","",$rs_order_list['consignee']);//收货人
		$arr_order['receiver'] = str_replace("'"," ",$arr_order['receiver']);//收货人
		$arr_order['receiverContact'] = str_replace("\\","",$rs_order_list['consignee']);//receiverContact
		$arr_order['receiverContact'] = str_replace("'"," ",$arr_order['receiverContact']);//receiverContact
		if(!empty($rs_order_list['tel'])){
			$phone = $rs_order_list['tel'];
		}else{
			$phone = $rs_order_list['mobile'];
		}
		if($phone){
			$arr_order['receiverContactTel'] = $phone;//联系人电话
		}else{
			$arr_order['receiverContactTel'] = "1111111111";//联系人电话 十位默认
		}

		$arr_order['receiverPostcode'] = $rs_order_list['zipcode'];//收货人邮编
		$arr_order['receiverAddress'] = $rs_order_list['address'];//收货地址
		$address = "";
		if($rs_order_list['address']){
			$address .= $rs_order_list['address'];
		}
		if(!empty($rs_order_list['address2'])){
			$address .= $rs_order_list['address2'];
		}
		$arr_order['receiverStreet'] = $address;//收货详细地址
		$arr_order['receiverCountry'] = $rs_order_list['country_code'];//收货人国家二字码(默认中国)
		$arr_order['receiverProvince'] = $rs_order_list['province'];// 收货人省份
		$arr_order['receiverCity'] = $rs_order_list['city'];//收货人城市
		$arr_order['receiverArea'] = "";//收货人区 非必填
		$arr_order['transpostSum'] = 0;//运费 默认都填写0
		foreach($goodslist as $k_goods=>$v_goods){
			$arr_order['items'][$k_goods]['productId'] = $v_goods['goods_sn'];//货品编号
			//$arr_order['items'][$k_goods]['productId'] = "16049-M";//测试 返回值salesOrderId = SOAFMWL17071700010
			$arr_order['items'][$k_goods]['planQty'] = $v_goods['goods_number'];//销售数量
			$arr_order['items'][$k_goods]['unitPrice'] = $v_goods['goods_price'];//销售单价
			$arr_order['items'][$k_goods]['stockStatus'] = "";//实物类别，默认合格品 非必填
			$arr_order['items'][$k_goods]['serialSign'] = "001";//商品记录项次(格式00X)
		}
		$arr_order['businessMemo'] = $rs_order_list['remark'];//订单备注
		$arr_order['receiveOrderTime'] = $rs_order_list['ordertime'];//销售时间
		$arr_order['warehouseId'] = $usaSupplierCode;//仓库编号 非必填
		$arr_order['warehouseName'] = "";//仓库名称 非必填
		$arr_order['orderSource'] = 16;//订单来源(API来源统一为16)
		$arr_order['paymentMethod'] = "";//非必填 支付方式（不填就默认04）
		$shipping_name = "";
		$shipping_id = 0;
		/**
		if($rs_order_list['salesOrderId']){    //不走该判断，因第一次已分仓
			$sql_express = "SELECT * FROM db_order_express WHERE name = '{$rs_order_list['shipping_name']}' ";
			$rs_express = $this->db->query($sql_express)->row_array();
			if(!empty($rs_express['oversea_express'])){
				$shipping_name = $rs_express['name'];
				//$arr_order['channelId'] = $rs_express['oversea_express'] ; //当为更改后的
			}else{
				//$arr_order['channelId'] = "UPS-G-I" ; //默认发货方式
				$arr_order['channelId'] = "" ; //默认发货方式
			}
		}else{
			$sql_express = "SELECT * FROM db_order_express WHERE oversea_express = 'UPS-G-I' ";
			$rs_express = $this->db->query($sql_express)->row_array();
			if($rs_express){
				$shipping_id = $rs_express['id'];
				$shipping_name = $rs_express['name'];
			}
			$arr_order['channelId'] = "" ; //默认发货方式 DHLPEU
		}**/

		$sql_express = "SELECT * FROM db_order_express WHERE oversea_express = '{$deliver}' ";
		$rs_express = $this->db->query($sql_express)->row_array();
		if($rs_express){
			$shipping_id = $rs_express['id'];
			$shipping_name = $rs_express['name'];
		}
		$arr_order['channelId'] = "" ; //默认发货方式 DHLPEU




		$arr_order['channelId'] = "";//非必填 渠道ID 如传值请用大写字母）  api要求暂时不填写
		$arr_order['transportNo'] = "";//非必填 运单号
		$arr_order['shortAddress'] = "";//非必填 大头笔
		$arr_order['originCode'] = "";//非必填 原寄地
		$arr_order['destCode'] = "";//非必填 目的地
		$arr_order['distributAddress'] = "";//集包地 非必填
		$arr_order['paymentSum'] = $rs_order_list['goods_amount'];//卖家应付金额 非必填
		$arr_order['transportNo'] = "";//运单号 非必填
		$post_data = json_encode($arr_order);
		//print_r($post_data);exit;
		//echo $post_data;exit;
		//echo $url;exit;
		//发送请求
		$post_arr_result = $this->sendCurlPostRequest($url,$post_data,$headers); //返回数组值
		//print_r($post_data);echo "<br/>";
		if(!empty($post_arr_result)){
			//返回值判断
			$sql_oversea = "SELECT * FROM db_order_oversea WHERE order_id = ".$rs_order_list['order_id'];
			$rs_oversea  = $this->db->query($sql_oversea)->row_array();
			if($post_arr_result['errorCode']==0){
				$salesOrderId = $post_arr_result['data']['salesOrderId'];
				if(!empty($rs_oversea)){
					$this->db->update("db_order_oversea",array("salesOrderId"=>$salesOrderId,"isSuccess"=>1),"order_id='".$rs_order_list["order_id"]."'");
				}else{
					$arr_oversea['order_id'] = $rs_order_list['order_id'];
					$arr_oversea['order_sn'] = $rs_order_list['order_sn'];
					$arr_oversea['salesOrderId'] = $salesOrderId;
					$arr_oversea['isSuccess'] = 1;
					$arr_oversea['addTime'] = date("Y-m-d H:i:s");
					$this->db->insert('db_order_oversea',$arr_oversea);
				}
				//更新日志表db_goods_log
				$imgdata["goods_id"] = $rs_order_list['order_id'];	//订单ID db_order_list
				$imgdata["updatetime"] = date("Y-m-d H:i:s");
				$imgdata["createUid"] = 0;
				$imgdata["types"] = 3;
				$imgdata["content"] = 'EZGO美国仓标配货成功,交易ID='.$rs_order_list['order_sn'];
				$imgdata["createUser"] ='auto';
				$this->db->insert('db_goods_log', $imgdata);

				//3代表美国仓 db_order_list shipping_status
				//$this->db->update("db_order_list",array("shipping_status"=>3,"salesOrderId"=>$salesOrderId,"is_nodelivery"=>1),"order_id='".$rs_order_list["order_id"]."'");
				$this->db->update("db_order_list",array("shipping_status"=>3,"salesOrderId"=>$salesOrderId,"is_nodelivery"=>1,"order_status"=>3,"shipping_name"=>$shipping_name,"shipping_id"=>$shipping_id),"order_id='".$rs_order_list["order_id"]."'");
			}else{
				$salesOrderId = $post_arr_result['data']['salesOrderId'];
				$errorMessage = $post_arr_result['errorMsg']; //错误信息
				if(!empty($rs_oversea)){
					$this->db->update("db_order_oversea",array("salesOrderId"=>$salesOrderId,"errorMessage"=>$errorMessage),"order_id='".$rs_order_list["order_id"]."'");
				}else{
					$arr_oversea['order_id'] = $rs_order_list['order_id'];
					$arr_oversea['order_sn'] = $rs_order_list['order_sn'];
					$arr_oversea['salesOrderId'] = $salesOrderId;
					$arr_oversea['errorMessage'] = $errorMessage;
					//$arr_oversea['isSuccess'] = 0; //默认值为0
					$arr_oversea['addTime'] = date("Y-m-d H:i:s");
					$this->db->insert('db_order_oversea',$arr_oversea);
				}
				//更新日志表db_goods_log 这样会有多条记录不能这么执行
				/**
				$imgdata["goods_id"] = $rs_order_list['order_id'];	//订单ID db_order_list
				$imgdata["updatetime"] = date("Y-m-d H:i:s");
				$imgdata["createUid"] = 0;
				$imgdata["types"] = 3;
				$imgdata["content"] = 'EZGO美国仓,'.$errorMessage;
				$imgdata["createUser"] ='auto';
				$this->db->insert('db_goods_log', $imgdata);
				 * */

			}


		}
	}
	//德国仓发货
	 private function doSendGoodsByDeWarehouse(& $rs_order_list,& $goodslist,$deliver="DHLPEU"){
		/**
		 $order_id_id = 9923;
		 //通用订单数据
		 $sql_order_list = "SELECT * FROM `db_order_list` WHERE order_id = '".$order_id_id."'";
		 $rs_order_list = $this->db->query($sql_order_list)->row_array();
		 //商品信息
		 $sql_order_sell = "SELECT * FROM db_order_sell a LEFT JOIN db_goods_stock b ON a.goods_id = b.goods_id WHERE a.order_id = '".$order_id_id."'";
		 $goodslist = $this->db->query($sql_order_sell)->result_array();
		**/
		//测试德国仓
		$url = "https://yinghuaglobal.de/Token";
		$username = $this->CI->config->item('germanyusername');
		$password = $this->CI->config->item('germanypass');
		//获取token
		$post_data = array ("username" => $username,"password" => $password,'grant_type'=>'password');
		$post_data = http_build_query($post_data);
		$headers = array("Content-type: Application/x-www-form-urlencoded;charset=utf-8");
		$post_arr_result = $this->sendCurlPostRequest($url,$post_data,$headers);
		//result['access_token']
		$token = $post_arr_result['access_token'];
        //$token="sjsX1gy29wh9wsJIlDGNJtHMj8n5eRNGAtT6k8iLcLLB3BAL7OgTDbOQk4FWlRdFnZ5KN-yyYUisxkhD5eTL5U2-Whyq8wNSaShho7miGRwX4tE1X20zfGtI-eNW28F6aEt8IrG9QvM5TqoxGLrm8lKCU7hKxDgMtgJJXvbVsBq_k8eklJaq5nuqaWf3CtGF9wplBM5JEd3-0lbmyuqXyxJQy1df-OcVSlcdPuOs2URp6eOa_3uTWspfnqzFaiU4xyu9qi6QFbl_jcW_wfsYcQnEEzkt_IGUGRgJzKNdd0Cxid8m6ZY-7ekPD7Y2urTAp4tujzpJbmCNZNeyfM85ObsLl8O12LUDwPw3zbXpXziGtO6Jdi8lJI2VOEiTCD_tVdIM8H31Q4wMgk06b2FrmmOzGKazmDsqqjpvFT-c3Qpc1gZPh7-VY1g64x3qX5qRANHItPstYeQQFIfNy09lmL4hL4CwXhArLxKYNnsJhrTadXYg3M-EUe_z72BFP98umGkc0GIwKU68gH2CmqTq4jTpg3";
        //echo $token;exit;
		//正式请求 上传新订单
		//$stocks_url = "https://yinghua.co.de/wms/Dispatches";
		//获取当前可用的邮递服务
		//$stocks_url = "https://yinghua.co.uk/wms/DeliveryServices";
		//$get_arr_result = $this->sendCurlGetRequest($stocks_url,$token);
		//print_r($get_arr_result);exit;
		$arr_order['OrderNumber'] = $rs_order_list['order_sn'];
		//收件人信息
		$arr_order['Surname'] = $rs_order_list['consignee'];//收货人
		$arr_order['FirstName'] = $rs_order_list['consignee'];
		//$arr_order['Building'] = "";//非必填
		$address = "";
		if($rs_order_list['address']){
			$address .= $rs_order_list['address'] ; //当为更改后的
		}
		if($rs_order_list['address2']){
			$address .= " ".$rs_order_list['address2'] ;
		}
		 $address = addslashes($address);
		//$arr_order['Street'] = $address;
		//$arr_order['Area'] = "";//非必填
		 if(strlen($address)>35){
			 $arr_order['Building'] = substr($address,35);//非必填
			 $arr_order['Street'] = substr($address,0,35);
			 $arr_order['Area'] = '';//非必填
		 }else{
			 $arr_order['Building'] = "";//非必填
			 $arr_order['Street'] = $address;
			 $arr_order['Area'] = '';//非必填
		 }

		$arr_order['City'] = $rs_order_list['city'];
		$arr_order['PostCode'] = $rs_order_list['zipcode'];
		$arr_order['Country'] = $rs_order_list['country_code'];
		$arr_order['Phone'] = $rs_order_list['tel'];
		$arr_order['Mobile'] = $rs_order_list['mobile'];
		$arr_order['Email'] = $rs_order_list['paypalmail'];//非必填
		 $shipping_name = "";
		 $shipping_id = 0;
		 /**
		if($rs_order_list['salesOrderId']){
			$sql_express = "SELECT * FROM db_order_express WHERE name = '{$rs_order_list['shipping_name']}' ";
			$rs_express = $this->db->query($sql_express)->row_array();
			if($rs_express['oversea_express']){
				$shipping_name = $rs_express['name'] ; //当为更改后的
				$arr_order['DeliveryServiceCode'] = $rs_express['oversea_express'] ; //当为更改后的
			}else{
				$arr_order['DeliveryServiceCode'] = "DHLPEU" ; //默认发货方式
			}

		}else{
			$sql_express = "SELECT * FROM db_order_express WHERE oversea_express = 'DHLPEU' ";
			$rs_express = $this->db->query($sql_express)->row_array();
			if($rs_express){
				$shipping_id = $rs_express['id'];
				$shipping_name = $rs_express['name'];
			}
			$arr_order['DeliveryServiceCode'] = "DHLPEU" ; //默认发货方式 DHLPEU
		}**/

		 $sql_express = "SELECT * FROM db_order_express WHERE oversea_express = '{$deliver}' ";
		 $rs_express = $this->db->query($sql_express)->row_array();
		 if($rs_express){
			 $shipping_id = $rs_express['id'];
			 $shipping_name = $rs_express['name'];
		 }
		 $arr_order['DeliveryServiceCode'] = $deliver ; //默认发货方式 DHLPEU






		//$post_data['Items'] = ;
		foreach($goodslist as $k_g=>$k_v){
			$arr_order['Items'][$k_g]['Barcode'] = $k_v['goods_sn'];
			$arr_order['Items'][$k_g]['Quantity'] = $k_v['goods_number'];
		}
        $post_order_arr = array($arr_order);
        $order_json = json_encode($post_order_arr);
        //echo json_encode($arr_order);exit;

		 $header = array("Authorization: Bearer {$token}","Content-type: Application/json;charset=utf-8");

		//正式请求  若存在则更新，否则上传新订单
		 /**
		if($rs_order_list['salesOrderId']){
		    $json = json_encode($arr_order);
			$stocks_url="https://yinghuaglobal.de/wms/Dispatches/{$rs_order_list['salesOrderId']}";
		    $res_arr = $this->sendCurlCommonRequest($stocks_url,"put",$json,$header);
			//应当返回状态 200
			if($res_arr==200||$res_arr==204){
					$imgdata["content"] = '英华德国仓更新成功,交易ID='.$rs_order_list['order_sn'];
			}else{
					$imgdata["content"] = '英华德国仓更新失败,交易ID='.$rs_order_list['order_sn'];
			}
			$this->db->update("db_order_list",array("shipping_status"=>2,"salesOrderId"=>$rs_order_list['salesOrderId'],"is_nodelivery"=>1,"order_status"=>3,"shipping_name"=>$shipping_name),"order_id='".$rs_order_list["order_id"]."'");
			//更新日志表db_goods_log
			$imgdata["goods_id"] = $rs_order_list['order_id'];	//订单ID db_order_list
			$imgdata["updatetime"] = date("Y-m-d H:i:s");
			$imgdata["createUid"] = 0;
			$imgdata["types"] = 3;
			$imgdata["createUser"] ='auto';
			$this->db->insert('db_goods_log', $imgdata);
			//var_dump($res_arr);
			//exit;
		}else{
			$stocks_url = "https://yinghuaglobal.de/wms/Dispatches";
		    $res_arr = $this->sendCurlPostRequest($stocks_url,$order_json,$header);
		}**/

		 $stocks_url = "https://yinghuaglobal.de/wms/Dispatches";
		 $res_arr = $this->sendCurlPostRequest($stocks_url,$order_json,$header);

		//返回值判断
		if(!empty($res_arr[0])){
			//返回值判断
			$sql_oversea = "SELECT * FROM db_order_oversea WHERE order_id = ".$rs_order_list['order_id'];
			$rs_oversea  = $this->db->query($sql_oversea)->row_array();
			if($res_arr[0]['Status']==200||$res_arr[0]['Status']==204){
				//UserID 客户订单号 客户提供的订单号
				$salesOrderId = $res_arr[0]['SystemID']; //订单对应的发货单号 用于查询是否发货等信息
				if(!empty($rs_oversea)){
					$this->db->update("db_order_oversea",array("salesOrderId"=>$salesOrderId,"isSuccess"=>1),"order_id='".$rs_order_list["order_id"]."'");
				}else{
					$arr_oversea['order_id'] = $rs_order_list['order_id'];
					$arr_oversea['order_sn'] = $rs_order_list['order_sn'];
					$arr_oversea['salesOrderId'] = $salesOrderId;
					$arr_oversea['isSuccess'] = 1;
					$arr_oversea['addTime'] = date("Y-m-d H:i:s");
					$this->db->insert('db_order_oversea',$arr_oversea);
				}

				//更新日志表db_goods_log
				$imgdata["goods_id"] = $rs_order_list['order_id'];	//订单ID db_order_list
				$imgdata["updatetime"] = date("Y-m-d H:i:s");
				$imgdata["createUid"] = 0;
				$imgdata["types"] = 3;
				$imgdata["content"] = '英华德国仓标配货成功,交易ID='.$rs_order_list['order_sn'];
				$imgdata["createUser"] ='auto';
				$this->db->insert('db_goods_log', $imgdata);

				//2代表德国仓 db_order_list shipping_status
				//$this->db->update("db_order_list",array("shipping_status"=>2,"salesOrderId"=>$salesOrderId,"shipping_name"=>"DHLPEU","is_nodelivery"=>1),"order_id='".$rs_order_list["order_id"]."'");
				$this->db->update("db_order_list",array("shipping_status"=>2,"salesOrderId"=>$salesOrderId,"is_nodelivery"=>1,"order_status"=>3,"shipping_name"=>$shipping_name,"shipping_id"=>$shipping_id),"order_id='".$rs_order_list["order_id"]."'");
			}else{
				$salesOrderId = $res_arr[0]['SystemID']; //订单对应的发货单号 用于查询是否发货等信息
				$errorMessage = $res_arr[0]['Message']; //错误信息
				if(!empty($rs_oversea)){
					$this->db->update("db_order_oversea",array("salesOrderId"=>$salesOrderId,"errorMessage"=>$errorMessage),"order_id='".$rs_order_list["order_id"]."'");
				}else{
					$arr_oversea['order_id'] = $rs_order_list['order_id'];
					$arr_oversea['order_sn'] = $rs_order_list['order_sn'];
					$arr_oversea['salesOrderId'] = $salesOrderId;
					$arr_oversea['errorMessage'] = $errorMessage;
					//$arr_oversea['isSuccess'] = 0; //默认值为0
					$arr_oversea['addTime'] = date("Y-m-d H:i:s");
					$this->db->insert('db_order_oversea',$arr_oversea);
				}
				//更新日志表db_goods_log
				$imgdata["goods_id"] = $rs_order_list['order_id'];	//订单ID db_order_list
				$imgdata["updatetime"] = date("Y-m-d H:i:s");
				$imgdata["createUid"] = 0;
				$imgdata["types"] = 3;
				$imgdata["content"] = '英华德国仓标配货成功,交易ID='.$rs_order_list['order_sn'].",".$errorMessage.$res_arr[0]['Status'];
				$imgdata["createUser"] ='auto';
				$this->db->insert('db_goods_log', $imgdata);

				$this->db->update("db_order_list",array("shipping_status"=>2,"salesOrderId"=>$salesOrderId,"is_nodelivery"=>1,"order_status"=>3,"shipping_name"=>$shipping_name,"shipping_id"=>$shipping_id),"order_id='".$rs_order_list["order_id"]."'");
			}

		}
	}
	//万邑通美西仓发货
	private function doSendGoodsByWinitWarehouse(& $rs_order_list,& $goodslist,$deliver="1000111"){
		//万邑通 测试账号
		/**
		$url = "http://erp.sandbox.winit.com.cn/ADInterface/api";
		$username = "rebecca";
		$password = "888";
		$token = "89435277FA3BA272DE795559998E-";
		 * */
		$date = date("Y-m-d H:i:s");
		//1.万邑通美西仓  正式环境账号
		$url = "http://api.winit.com.cn/ADInterface/api";
		$username = $this->CI->config->item('winitusername');
		//$password = $this->CI->config->item('winitpass');
		$token = $this->CI->config->item('winittoken');
		//提交相关订单数据 美西仓 按照签名顺序来组合，不然签名通不过
		$arr_order['address1'] = $rs_order_list['address'];
		$arr_order['address2'] = $rs_order_list['address2'];//非必填
		$arr_order['city'] = $rs_order_list['city'];

		//获取运单号是返回的值 [deliverywayId] => 1000111
		$arr_order['deliveryWayID'] = $deliver;


		//$arr_order['deliveryWayID'] = "1000111";
		//$arr_order['deliveryWayID'] = "2000003"; //最后一公里派送方式ID。最后一公里派送方式ID不可为空。可查询
		$arr_order['eBayOrderID '] = $rs_order_list['order_sn']; // 非必填项
		$arr_order['emailAddress'] = $rs_order_list['paypalmail'];//非必填
		$arr_order['insuranceTypeID'] = "1000000";//最后一公里派送方式所用保险类型ID。保险类型ID不可为空。默认为1000000
		if(!empty($rs_order_list['tel'])){
			$phone = $rs_order_list['tel'];
		}else{
			$phone = $rs_order_list['mobile'];
		}
		$arr_order['phoneNum'] = $phone;
		foreach($goodslist as $k=>$v){
			$arr_order['productList'][$k]['eBayBuyerID'] = "";//非必填
			$arr_order['productList'][$k]['eBayItemID'] = "";//非必填
			$arr_order['productList'][$k]['eBaySellerID'] = "";//非必填
			$arr_order['productList'][$k]['eBayTransactionID'] = ""; //非必填
			$arr_order['productList'][$k]['productCode'] = $v['goods_sn'];
			//$arr_order['productList'][$k]['productCode'] = "auto_sku52"; //测试
			$arr_order['productList'][$k]['productNum'] = $v['goods_number'];
			$arr_order['productList'][$k]['specification'] = "";//非必填 规格（如果此产品注册时填写了该字段，那么此为必填项，否则无法准确定位您注册的产品)如果您在注册产品时没有填写该字段，则在XML中去掉‘Specification’字段。）
		}
		//收件人相关信息
		$arr_order['recipientName'] = $rs_order_list['consignee'];//收货人
		$arr_order['region'] = $rs_order_list['province'];//收件人州名称。
		$arr_order['repeatable'] = "N";//用户授权此海外仓出库单是否可重复。是否允许重复不可为空。
		$arr_order['sellerOrderNo'] = $rs_order_list['order_sn']; //卖家订单号。 非必填项
		$arr_order['state'] = $rs_order_list['country_code'];//收件人国家名称，可使用国家英文全称或是ISO国家代码。
		$arr_order['warehouseID'] = "1000008";//万邑通海外仓ID，唯一，可查询。
		$arr_order['zipCode'] = $rs_order_list['zipcode'];
		$arr_order['isShareOrder'] = "";//非必填
		//$arr_order['doorplateNumbers'] = "";//派送方式为DHL、UK DPD，门牌号必填
		//$arr_order['platform'] = "";//非必填
		$arr_order['fromBpartnerId'] = "";//非必填

		//相关签名信息
		$post_data = array();
		//1.创建海外仓出库单（草稿）createOutboundInfo 2.创建海外仓出库单（确认中）createOutboundOrder
		//当出库单处在草稿状态中时，用户可通过API作废出库单。
		$post_data['action'] ="createOutboundOrder" ;
		$post_data['app_key'] = $username;
		$post_data['data'] = $arr_order;
		$post_data['format'] = "json";
		$post_data['language'] ="zh_CN";
		$post_data['platform'] = "SELLERERP";
		$post_data['sign_method'] = "md5";
		$post_data['timestamp'] = $date;
		$post_data['version'] = "1.0";
		//上述为签名所用字段
		$con_data = $token;
		$con_data.= "action".$post_data['action'].
			"app_key".$post_data['app_key'].
			"data".json_encode($post_data['data']).
			"format".$post_data['format'].
			"platform".$post_data['platform'].
			"sign_method".$post_data['sign_method'].
			"timestamp".$post_data['timestamp'].
			"version".$post_data['version'];
		$con_data.= $token;
		$sign = strtoupper(md5($con_data));
		$post_data['sign'] = $sign;
		$json_post = json_encode($post_data);
		//echo $json_post;exit;
		$post_arr_result = $this->sendCurlPostRequest($url,$json_post,$headers=array());
		//返回值  Array ( [code] => 0 [data] => Array ( [outboundOrderNum] => WO0000002520 ) [msg] => 成功 )
		//重复提交 Array ( [code] => 2020240140 [data] => [msg] => 当前卖家订单号与订单[WO0000002520]重复 )
		//print_r($post_arr_result);exit;
		if(!empty($post_arr_result)){
			//返回值判断
			$sql_oversea = "SELECT * FROM db_order_oversea WHERE order_id = ".$rs_order_list['order_id'];
			$rs_oversea  = $this->db->query($sql_oversea)->row_array();
			if($post_arr_result['code']==0){
				$salesOrderId = $post_arr_result['data']['outboundOrderNum'];
				if(!empty($rs_oversea)){
					$this->db->update("db_order_oversea",array("salesOrderId"=>$salesOrderId,"isSuccess"=>1),"order_id='".$rs_order_list["order_id"]."'");
				}else{
					$arr_oversea['order_id'] = $rs_order_list['order_id'];
					$arr_oversea['order_sn'] = $rs_order_list['order_sn'];
					$arr_oversea['salesOrderId'] = $salesOrderId;
					$arr_oversea['isSuccess'] = 1;
					$arr_oversea['addTime'] = date("Y-m-d H:i:s");
					$this->db->insert('db_order_oversea',$arr_oversea);
				}
				//更新日志表db_goods_log
				$imgdata["goods_id"] = $rs_order_list['order_id'];	//订单ID db_order_list
				$imgdata["updatetime"] = date("Y-m-d H:i:s");
				$imgdata["createUid"] = 0;
				$imgdata["types"] = 3;
				$imgdata["content"] = '万邑通美西仓标配货成功,交易ID='.$rs_order_list['order_sn'];
				$imgdata["createUser"] ='auto';
				$this->db->insert('db_goods_log', $imgdata);


				//4代表万邑通 美西仓 db_order_list shipping_status
				//$this->db->update("db_order_list",array("shipping_status"=>4,"salesOrderId"=>$salesOrderId,"is_nodelivery"=>1),"order_id='".$rs_order_list["order_id"]."'");
				$this->db->update("db_order_list",array("shipping_status"=>4,"salesOrderId"=>$salesOrderId,"is_nodelivery"=>1,"order_status"=>3),"order_id='".$rs_order_list["order_id"]."'");
			}else{
				$salesOrderId = $post_arr_result['data']['outboundOrderNum'];
				$errorMessage = $post_arr_result['msg']; //错误信息
				if(!empty($rs_oversea)){
					$this->db->update("db_order_oversea",array("salesOrderId"=>$salesOrderId,"errorMessage"=>$errorMessage),"order_id='".$rs_order_list["order_id"]."'");
				}else{
					$arr_oversea['order_id'] = $rs_order_list['order_id'];
					$arr_oversea['order_sn'] = $rs_order_list['order_sn'];
					$arr_oversea['salesOrderId'] = $salesOrderId;
					$arr_oversea['errorMessage'] = $errorMessage;
					//$arr_oversea['isSuccess'] = 0; //默认值为0
					$arr_oversea['addTime'] = date("Y-m-d H:i:s");
					$this->db->insert('db_order_oversea',$arr_oversea);
				}
			}

		}
	}
	//美国仓，德国仓，英国仓 发货运单号
	public function getDeliverNumberOversea(){
		//轮询获取相关海外仓库发货的订单  1英国仓，2德国仓，3EZGO美国仓 4万邑通美西仓
		/** 美国暂时不用 暂时注释，说不定以后会用 8/22
		$sql = "SELECT GROUP_CONCAT(salesOrderId) as salesOrderId FROM db_order_list WHERE shipping_status = 3 AND shipping_number is NULL ";
		//新建一数据库后的sql语句
		//$sql = "SELECT GROUP_CONCAT(a.salesOrderId) as salesOrderId FROM db_order_oversea a LEFT JOIN db_order_list b On a.order_id = b.order_id  WHERE a.shipping_status = 3 AND b.shipping_number is NULL ";
		$rs = $this->db->query($sql)->row_array();
		//$rs['salesOrderId'] = "SIFMWL17070700001";  // 测试 功能正常，之前已上传订单
		//$rs['salesOrderId'] = "SOAFMWL17071700010"; //自己上传订单，未经他们处理，无法查询
		if(!empty($rs['salesOrderId'])){
			$salesOrderId_arr = array("salesOrderId"=>$rs['salesOrderId']);
			//1.美国仓  正式环境账号 测试环境已停用
			$customerId = $this->CI->config->item('goodscode');
			$token = $this->CI->config->item('usatoken');
			$usaSupplierCode = $this->CI->config->item('usasuppliercode');
			//查询发货运单信息，支持批量查询
			// selectBySmSalerOrder 多条件查询 searchSmSalerOrderFinish
			$url = "http://openapi.4pis.com:8080/api/service/wmc/order/searchSmSalerOrderFinish?token=$token&customerId=$customerId&language=zh_CN";
			$headers= array("Content-type: Application/json;charset=utf-8");
			$post_data = json_encode($salesOrderId_arr);
			$ret_arr = $this->sendCurlPostRequest($url,$post_data,$headers);
			//print_r($ret_arr);exit;
			if($ret_arr['errorCode']==0){
					foreach($ret_arr['data'] as $kk=>$vv){
						//orderStatus 单据状态 (95已发货，94发货出库中）
						if(!empty($vv['transportNo'])&&$vv['orderStatus']==95){
							//查询运费
							$url = "http://openapi.4pis.com:8080/api/service/wmc/order/selectBySmSalerOrder?token=$token&customerId=$customerId&language=zh_CN";
							$headers= array("Content-type: Application/json;charset=utf-8");
							$post_data = json_encode($salesOrderId_arr);
							$ret_ary = $this->sendCurlPostRequest($url,$post_data,$headers);
							if($ret_ary['errorCode']==0){
								foreach($ret_ary['data'] as $ka=>$va){
									//运费 transpostSum
									$charge = $va["transpostSum"];
									//美元USD 查询汇率
									$sql_eur = "SELECT * FROM d_moneyrate WHERE name = 'USD' ";
									$rs_eur  = $this->db->query($sql_eur)->row_array();
									$shipping_fee = $charge*$rs_eur['rate'];
									//查询货运方式显示名
									$sql_oversea = "SELECT * FROM db_order_express WHERE oversea_express = '{$vv['motorcadeName']}' ";
									$rs_oversea  = $this->db->query($sql_oversea)->row_array();

									$this->db->update("db_order_list",array("shipping_number"=>$vv['transportNo'],"shipping_name"=>$rs_oversea['name'],"shipping_id"=>$rs_oversea['id'],"shipping_originask"=>$charge,"shipping_fee"=>$shipping_fee,"order_status"=>4),"salesOrderId='".$vv["salerOrderId"]."'");
								}
							}else{
								$this->db->update("db_order_list",array("shipping_number"=>$vv['transportNo'],"shipping_name"=>$vv['motorcadeName'],"order_status"=>4),"salesOrderId='".$vv["salerOrderId"]."'");
							}
							//$this->db->update("db_order_list",array("shipping_number"=>$vv['transportNo'],"shipping_name"=>$vv['motorcadeName'],"shipping_originask"=>$charge,"order_status"=>4),"salesOrderId='".$vv["salerOrderId"]."'");
							//更新库存信息
							/**
							$sql_stock_uk = "SELECT * FROM db_order_sell a LEFT JOIN db_order_list b ON a.order_id = b.order_id WHERE a.salesOrderId = '".$vv["salerOrderId"]."'";
							$rs_stock_uk = $this->db->query($sql_stock_uk)->result_array();
							if(!empty($rs_stock_uk)){
								foreach($rs_stock_uk as $k=>$v){
									$this->db->set("stock = stock -",$v["goods_number"]);
									//$this->db->set('field', 'field+1');
									$this->db->where("goods_id",$v["goods_id"]);
									$this->db->update("db_goods_stock");
								}
							}**/
		/** 注释
						}
					}
			}
		}**/
		//英国海外仓仓库相关发货数据
		$sql_uk = "SELECT GROUP_CONCAT(salesOrderId) as salesOrderId FROM db_order_list WHERE shipping_status = 1 AND shipping_number is NULL ";
		$rs_uk = $this->db->query($sql_uk)->row_array();
		//$rs_uk['salesOrderId'] = "D17060228472"; //测试 登录后台查看 测试成功 后台数据
		if(!empty($rs_uk['salesOrderId'])){
			$url = "https://yinghua.co.uk/Token";
			$username = $this->CI->config->item('ukusername');
			$password = $this->CI->config->item('ukpass');
			//获取token
			$post_data = array ("username" => $username,"password" => $password,'grant_type'=>'password');
			$post_data = http_build_query($post_data);
			$headers = array("Content-type: Application/x-www-form-urlencoded;charset=utf-8");
			$post_arr_result = $this->sendCurlPostRequest($url,$post_data,$headers);
			$token = $post_arr_result['access_token'];
			//正式请求 上传新订单
			$arr_uk_order = explode(",",$rs_uk['salesOrderId']);
			foreach($arr_uk_order as $k_uk=>$v_uk){
				$stocks_url = "https://yinghua.co.uk/wms/Dispatches/{$v_uk}";
				$ret_arr = $this->sendCurlGetRequest($stocks_url,$token); //已经json返回了
				//print_r($ret_arr);exit;
				//Dispatched 已经发货状态
				if($ret_arr['OrderStatus']=="Dispatched"){
					// 或 "salesOrderId='".$ret_arr["DeliveryNumber"]
					$datetime = $ret_arr['DispatchTimeUTC']; //"2016-03-08T01:00:50.127",
					$timestamp = strtotime($datetime)+60*60*8;
					$date = date("Y-m-d H:i:s",$timestamp);
					$this->db->update("db_order_oversea",array("dispatchTime"=>$date)," salesOrderId = '".$v_uk."'");

					//查商品数，更新库存  3代表英华英国仓
					$uk_sql = "SELECT a.order_id,a.order_sn,b.goods_id,b.goods_sn,b.goods_number,c.stock,c.storage_id FROM db_order_list a ".
							  "LEFT JOIN db_order_sell b ON a.order_id = b.order_id ".
							  "LEFT JOIN db_goods_stock c ON b.goods_id = c.goods_id AND c.storage_id = 3 ".
							  "WHERE a.salesOrderId = '{$v_uk}' ";
					$uk_rs  = $this->db->query($uk_sql)->result_array();
					$sku_count = 0;
					$sku_list  = "";
					foreach($uk_rs as $key=>$value){
						$sku_count = $sku_count +1;
						$sku_list[]= $value['goods_sn'];

						if($value['storage_id']){ //说明数据库有该库存记录,若无库存记录，则不更新
							$stock = $value['stock']-$value['goods_number'];
							$this->db->update('db_goods_stock',array('stock'=>$stock),"goods_id = '{$value['goods_id']}' AND storage_id = 3 ");

							//更新相关日志信息
							$stocklog["goods_id"] = $value['order_id'];	//订单ID db_order_list
							$stocklog["updatetime"] = date("Y-m-d H:i:s");
							$stocklog["createUid"] = 0;
							$stocklog["types"] = 3;
							$stocklog["content"] = "英华英国仓发货成功,发货SKU：{$value['goods_sn']},发货数量：{$value['goods_number']},自动更新海外仓库存，{$value['stock']}-{$value['goods_number']} = {$stock} (剩余库存数) ";
							$stocklog["createUser"] ='auto';
							$this->db->insert('db_goods_log', $stocklog);

							//更新商品表日志
							$goodslog="";
							$goodslog["goods_id"] = $value['goods_id'];	//更新商品表 日志信息
							$goodslog["updatetime"] = date("Y-m-d H:i:s");
							$goodslog["createUid"] = 0;
							$goodslog["types"] = 1; //库存信息
							$goodslog["content"] = "英华英国仓发货成功,发货SKU：{$value['goods_sn']},发货数量：{$value['goods_number']},自动更新海外仓库存，{$value['stock']}-{$value['goods_number']} = {$stock} (剩余库存数) ".",订单号：".$value["order_sn"];
							$goodslog["createUser"] ="auto";
							$this->db->insert('db_goods_log', $goodslog);
						}
					}


					if(isset($ret_arr['TrackingNo'])){
						//运输费+手续费
						$charge = $ret_arr['DeliveryCharge']+$ret_arr['HandlingCharge'];
						//欧元EUR 查询汇率
						$sql_eur = "SELECT * FROM d_moneyrate WHERE name = 'EUR' ";
						$rs_eur  = $this->db->query($sql_eur)->row_array();
						$shipping_fee = $charge*$rs_eur['rate'];
						//查询货运方式显示名
						$sql_oversea = "SELECT * FROM db_order_express WHERE oversea_express = '{$ret_arr['DeliveryServiceCode']}' ";
						$rs_oversea  = $this->db->query($sql_oversea)->row_array();
						$current_time = time();
						$this->db->update("db_order_list",array("shipping_number"=>$ret_arr['TrackingNo'],"shipping_name"=>$rs_oversea['name'],"shipping_time"=>$current_time,"shipping_id"=>$rs_oversea['id'],"shipping_realfee"=>$shipping_fee,"order_status"=>4),"salesOrderId='".$v_uk."'");
					}else{
						$this->db->update("db_order_list",array("order_status"=>4),"salesOrderId='".$v_uk."'");
					}
					//更新日志表db_goods_log
					$sql_order = "SELECT * FROM db_order_list WHERE salesOrderId = '{$v_uk}' ";
					$rs_order = $this->db->query($sql_order)->row_array();
					$imgdata["goods_id"] = $rs_order['order_id'];	//订单ID db_order_list
					$imgdata["updatetime"] = date("Y-m-d H:i:s");
					$imgdata["createUid"] = 0;
					$imgdata["types"] = 3;
					$imgdata["content"] = '英华英国仓发货成功,交易ID='.$rs_order['order_sn'].",运单号：".$ret_arr['TrackingNo'];
					$imgdata["createUser"] ='auto';
					$this->db->insert('db_goods_log', $imgdata);

					//更新另外一张表 方便日后报表统计
					$postdata="";
					$postdata["batch_order_sn"] = $rs_order["order_sn"];
					$postdata["batch_shipping_number"] = $ret_arr['TrackingNo'];
					$postdata["batch_shipping_name"] = $rs_oversea['name'];
					$postdata["batch_orderweight"] = $rs_order['orderweight'];
					$postdata["oper"] = '沈龙';
					$postdata["opertime"] = date("Y-m-d H:i:s");
					$postdata["yz"] = 0;
					$postdata["skuNum"] = $sku_count;
					$postdata["skulist"] = ",".implode(",",$sku_list).",";
					$this->db->insert("db_order_batchexpress",$postdata);



					//更新库存信息
					/**
					$sql_stock_uk = "SELECT * FROM db_order_sell a LEFT JOIN db_order_list b ON a.order_id = b.order_id WHERE a.salesOrderId = '".$v_uk."'";
					$rs_stock_uk = $this->db->query($sql_stock_uk)->result_array();
					if(!empty($rs_stock_uk)){
						foreach($rs_stock_uk as $k=>$v){
							$this->db->set("stock = stock -",$v["goods_number"]);
							//$this->db->set('field', 'field+1');
							$this->db->where("goods_id",$v["goods_id"]);
							$this->db->update("db_goods_stock");

						}
					}**/

				}
				//print_r($get_arr_result);exit;
			}
		}
		//德国海外仓仓库相关发货信息
		$sql_de = "SELECT GROUP_CONCAT(salesOrderId) as salesOrderId FROM db_order_list WHERE shipping_status = 2 AND (shipping_number = '' or shipping_number is NULL ) ";
		$rs_de = $this->db->query($sql_de)->row_array();
		//print_r($rs_de);exit;
		//$rs_de['salesOrderId']="D17070049531"; //测试 发货单号 网站后台拿下来  测试成功 可以使用
		if(!empty($rs_de['salesOrderId'])){
			$url = "https://yinghuaglobal.de/Token";
			$username = $this->CI->config->item('germanyusername');
			$password = $this->CI->config->item('germanypass');
			//获取token
			$post_data = array ("username" => $username,"password" => $password,'grant_type'=>'password');
			$post_data = http_build_query($post_data);
			$headers = array("Content-type: Application/x-www-form-urlencoded;charset=utf-8");
			$post_arr_result = $this->sendCurlPostRequest($url,$post_data,$headers);
			$token = $post_arr_result['access_token'];
			//正式请求 上传新订单
			$arr_de_order = explode(",",$rs_de['salesOrderId']);
			foreach($arr_de_order as $k_de=>$v_de){
				$v_de = trim($v_de);
				$stocks_url = "https://yinghuaglobal.de/wms/Dispatches/{$v_de}";
				$ret_arr = $this->sendCurlGetRequest($stocks_url,$token);
				//Dispatched 已经发货状态
				if($ret_arr['OrderStatus']=="Dispatched"){
					// 或 "salesOrderId='".$ret_arr["DeliveryNumber"]

					$datetime = $ret_arr['DispatchTimeUTC']; //"2016-03-08T01:00:50.127",
					$timestamp = strtotime($datetime)+60*60*8;
					$date = date("Y-m-d H:i:s",$timestamp);
					$this->db->update("db_order_oversea",array("dispatchTime"=>$date)," salesOrderId = '".$v_de."'");

					//查商品数，更新库存  5代表英华德国仓
					$de_sql = "SELECT a.order_id,a.order_sn,b.goods_id,b.goods_sn,b.goods_number,c.stock,c.storage_id FROM db_order_list a ".
						"LEFT JOIN db_order_sell b ON a.order_id = b.order_id ".
						"LEFT JOIN db_goods_stock c ON b.goods_id = c.goods_id AND c.storage_id = 5 ".
						"WHERE a.salesOrderId = '{$v_de}' ";
					$de_rs  = $this->db->query($de_sql)->result_array();
					$sku_count = 0;
					$sku_list  = "";
					foreach($de_rs as $key=>$value){
						$sku_count = $sku_count +1;
						$sku_list[]= $value['goods_sn'];
						if($value['storage_id']){ //说明数据库有该库存记录,若无库存记录，则不更新
							$stock = $value['stock']-$value['goods_number'];
							$this->db->update('db_goods_stock',array('stock'=>$stock),"goods_id = '{$value['goods_id']}' AND storage_id = 5 ");

							//更新相关日志信息
							$stocklog["goods_id"] = $value['order_id'];	//订单ID db_order_list
							$stocklog["updatetime"] = date("Y-m-d H:i:s");
							$stocklog["createUid"] = 0;
							$stocklog["types"] = 3;
							$stocklog["content"] = "英华德国仓发货成功,发货SKU：{$value['goods_sn']},发货数量：{$value['goods_number']},自动更新海外仓库存，{$value['stock']}-{$value['goods_number']} = {$stock} (剩余库存数) ";
							$stocklog["createUser"] ='auto';
							$this->db->insert('db_goods_log', $stocklog);


							//更新商品表日志
							$goodslog="";
							$goodslog["goods_id"] = $value['goods_id'];	//更新商品表 日志信息
							$goodslog["updatetime"] = date("Y-m-d H:i:s");
							$goodslog["createUid"] = 0;
							$goodslog["types"] = 1; //库存信息
							$goodslog["content"] = "英华德国仓发货成功,发货SKU：{$value['goods_sn']},发货数量：{$value['goods_number']},自动更新海外仓库存，{$value['stock']}-{$value['goods_number']} = {$stock} (剩余库存数) ".",订单号：".$value["order_sn"];
							$goodslog["createUser"] ="auto";
							$this->db->insert('db_goods_log', $goodslog);


						}
					}


					//$this->db->update("db_order_list",array("shipping_number"=>$ret_arr['TrackingNo'],"shipping_name"=>$ret_arr['DeliveryServiceCode'],"order_status"=>4),"salesOrderId='".$v_de."'");
					if(isset($ret_arr['TrackingNo'])){
						//运输费+手续费
						$charge = $ret_arr['DeliveryCharge']+$ret_arr['HandlingCharge'];
						//欧元EUR 查询汇率
						$sql_eur = "SELECT * FROM d_moneyrate WHERE name = 'EUR' ";
						$rs_eur  = $this->db->query($sql_eur)->row_array();
						$shipping_fee = $charge*$rs_eur['rate'];
						//货运方式显示名
						//查询货运方式显示名
						$sql_oversea = "SELECT * FROM db_order_express WHERE oversea_express = '{$ret_arr['DeliveryServiceCode']}' ";
						$rs_oversea  = $this->db->query($sql_oversea)->row_array();
						$current_time = time();
						$this->db->update("db_order_list",array("shipping_number"=>$ret_arr['TrackingNo'],"shipping_name"=>$rs_oversea['name'],"shipping_time"=>$current_time,"shipping_id"=>$rs_oversea['id'],"shipping_realfee"=>$shipping_fee,"order_status"=>4),"salesOrderId='".$v_de."'");
					}else{
						$this->db->update("db_order_list",array("order_status"=>4),"salesOrderId='".$v_de."'");
					}
					//更新日志表db_goods_log
					$sql_order = "SELECT * FROM db_order_list WHERE salesOrderId = '{$v_de}' ";
					$rs_order = $this->db->query($sql_order)->row_array();
					$imgdata["goods_id"] = $rs_order['order_id'];	//订单ID db_order_list
					$imgdata["updatetime"] = date("Y-m-d H:i:s");
					$imgdata["createUid"] = 0;
					$imgdata["types"] = 3;
					$imgdata["content"] = '英华德国仓发货成功,交易ID='.$rs_order['order_sn'].",运单号：".$ret_arr['TrackingNo'];
					$imgdata["createUser"] ='auto';
					$this->db->insert('db_goods_log', $imgdata);

					//更新另外一张表 方便日后报表统计
					$postdata="";
					$postdata["batch_order_sn"] = $rs_order["order_sn"];
					$postdata["batch_shipping_number"] = $ret_arr['TrackingNo'];
					$postdata["batch_shipping_name"] = $rs_oversea['name'];
					$postdata["batch_orderweight"] = $rs_order['orderweight'];
					$postdata["oper"] = '沈龙';
					$postdata["opertime"] = date("Y-m-d H:i:s");
					$postdata["yz"] = 0;
					$postdata["skuNum"] = $sku_count;
					$postdata["skulist"] = ",".implode(",",$sku_list).",";
					$this->db->insert("db_order_batchexpress",$postdata);

					//更新库存信息
					/**
					$sql_stock_uk = "SELECT * FROM db_order_sell a LEFT JOIN db_order_list b ON a.order_id = b.order_id WHERE a.salesOrderId = '".$v_de."'";
					$rs_stock_uk = $this->db->query($sql_stock_uk)->result_array();
					if(!empty($rs_stock_uk)){
						foreach($rs_stock_uk as $k=>$v){
							$this->db->set("stock = stock -",$v["goods_number"]);
							//$this->db->set('field', 'field+1');
							$this->db->where("goods_id",$v["goods_id"]);
							$this->db->update("db_goods_stock");
						}
					}**/
				}
				//print_r($get_arr_result);exit;
			}
		}
		// 万邑通美西仓 仓库发货信息
		$sql = "SELECT GROUP_CONCAT(salesOrderId) as salesOrderId FROM db_order_list WHERE shipping_status = 4 AND shipping_number is NULL ";
		//新建一数据库后的sql语句
		//$sql = "SELECT GROUP_CONCAT(a.salesOrderId) as salesOrderId FROM db_order_oversea a LEFT JOIN db_order_list b On a.order_id = b.order_id  WHERE a.shipping_status = 4 AND b.shipping_number is NULL ";
		$rs = $this->db->query($sql)->row_array();
		//$rs['salesOrderId'] = "WO0000000108";  // 测试环境 功能正常，之前已上传订单
		if(!empty($rs['salesOrderId'])){
			$salesOrderId_arr = array("salesOrderId"=>$rs['salesOrderId']);
			$date = date("Y-m-d H:i:s");
			//测试相关账号密码
			//$url = "http://erp.sandbox.winit.com.cn/ADInterface/api";
			//$username = "rebecca";
			//$token = "89435277FA3BA272DE795559998E-";
			//1.万邑通美西仓  正式环境账号
			$url = "http://api.winit.com.cn/ADInterface/api";
			$username = $this->CI->config->item('winitusername');
			//$password = $this->CI->config->item('winitpass');
			$token = $this->CI->config->item('winittoken');
			//查询发货运单信息
			$arr_order['data'] = array("outboundOrderNum"=>$rs['salesOrderId']);
			$postData['action'] ="queryOutboundOrder" ;
			$postData['app_key'] = $username;
			$postData['data'] = $arr_order['data'];
			$postData['format'] = "json";
			$postData['language'] ="zh_CN";
			$postData['platform'] = "SELLERERP";
			$postData['sign_method'] = "md5";
			$postData['timestamp'] = $date;
			$postData['version'] = "1.0";
			//上述为签名所用字段
			$con_data = $token;
			$con_data.= "action".$postData['action'].
				"app_key".$postData['app_key'].
				"data".json_encode($postData['data']).
				"format".$postData['format'].
				"platform".$postData['platform'].
				"sign_method".$postData['sign_method'].
				"timestamp".$postData['timestamp'].
				"version".$postData['version'];
			$con_data.= $token;
			$sign = strtoupper(md5($con_data));
			$postData['sign'] = $sign;
			$json_post = json_encode($postData);
			$ret_arr = $this->sendCurlPostRequest($url,$json_post,$headers=array());
			if($ret_arr['code']==0){
				foreach($ret_arr['data']['list'] as $kk=>$vv){
					//status 单据状态 派送中
					if($vv['status']=="DLI"){

						$datetime = $vv['outboundDate']; //"2014-07-08 17:41:59",
						$timestamp = strtotime($datetime)+60*60*8;
						$date = date("Y-m-d H:i:s",$timestamp);
						$this->db->update("db_order_oversea",array("dispatchTime"=>$date)," salesOrderId = '".$vv["outboundOrderNum"]."'");

						//查商品数，更新库存  5代表英华德国仓
						$us_sql = "SELECT a.order_id,a.order_sn,b.goods_id,b.goods_sn,b.goods_number,c.stock,c.storage_id FROM db_order_list a ".
							"LEFT JOIN db_order_sell b ON a.order_id = b.order_id ".
							"LEFT JOIN db_goods_stock c ON b.goods_id = c.goods_id AND c.storage_id = 7 ".
							"WHERE a.salesOrderId = '{$vv["outboundOrderNum"]}' ";
						$us_rs  = $this->db->query($us_sql)->result_array();
						$sku_count = 0;
						$sku_list  = "";
						foreach($us_rs as $key=>$value){
							$sku_count = $sku_count +1;
							$sku_list[]= $value['goods_sn'];
							if($value['storage_id']){ //说明数据库有该库存记录,若无库存记录，则不更新
								$stock = $value['stock']-$value['goods_number'];
								$this->db->update('db_goods_stock',array('stock'=>$stock),"goods_id = '{$value['goods_id']}' AND storage_id = 7 ");

								//更新相关日志信息
								$stocklog["goods_id"] = $value['order_id'];	//订单ID db_order_list
								$stocklog["updatetime"] = date("Y-m-d H:i:s");
								$stocklog["createUid"] = 0;
								$stocklog["types"] = 3;
								$stocklog["content"] = "万邑通美西仓发货成功,发货SKU：{$value['goods_sn']},发货数量：{$value['goods_number']},自动更新海外仓库存，{$value['stock']}-{$value['goods_number']} = {$stock} (剩余库存数) ";
								$stocklog["createUser"] ='auto';
								$this->db->insert('db_goods_log', $stocklog);

								//更新商品表日志
								$goodslog="";
								$goodslog["goods_id"] = $value['goods_id'];	//更新商品表 日志信息
								$goodslog["updatetime"] = date("Y-m-d H:i:s");
								$goodslog["createUid"] = 0;
								$goodslog["types"] = 1; //库存信息
								$goodslog["content"] = "万邑通美西仓发货成功,发货SKU：{$value['goods_sn']},发货数量：{$value['goods_number']},自动更新海外仓库存，{$value['stock']}-{$value['goods_number']} = {$stock} (剩余库存数) ".",订单号：".$value["order_sn"];
								$goodslog["createUser"] ="auto";
								$this->db->insert('db_goods_log', $goodslog);
							}
						}





						//费用需要通过特定海外仓接口查询
						$charge = $vv['totalCost'];
						//美元USD 查询汇率
						//$usd = $vv['handlingfeeCode']; //获取的货币符号 默认USD
						$sql_eur = "SELECT * FROM d_moneyrate WHERE name = 'USD' ";
						$rs_eur  = $this->db->query($sql_eur)->row_array();
						$shipping_fee = $charge*$rs_eur['rate'];

						//查询货运方式显示名 [deliverywayId] => 1000111  [carrier] => UPS
						//暂时 US UPS Ground
						$vv['deliverywayName'] = "US UPS Ground"; //实际为 [deliverywayName] => UPS GROUND SERVICE  [winitProductCode] => OSF810595
						$sql_oversea = "SELECT * FROM db_order_express WHERE name = '{$vv['deliverywayName']}' ";
						$rs_oversea  = $this->db->query($sql_oversea)->row_array();
						$current_time = time();
						//$this->db->update("db_order_list",array("shipping_number"=>$ret_arr['TrackingNo'],"shipping_name"=>$rs_oversea['name'],"shipping_id"=>$rs_oversea['id'],"shipping_realfee"=>$shipping_fee,"order_status"=>4),"salesOrderId='".$vv["outboundOrderNum"]."'");
						$this->db->update("db_order_list",array("shipping_number"=>$vv['trackingNum'],"shipping_name"=>$vv['deliverywayName'],"shipping_time"=>$current_time,"shipping_id"=>$rs_oversea['id'],"shipping_realfee"=>$shipping_fee,"order_status"=>4),"salesOrderId='".$vv["outboundOrderNum"]."'");

						//更新日志表db_goods_log
						$sql_order = "SELECT * FROM db_order_list WHERE salesOrderId = '{$vv['outboundOrderNum']}' ";
						$rs_order = $this->db->query($sql_order)->row_array();
						$imgdata["goods_id"] = $rs_order['order_id'];	//订单ID db_order_list
						$imgdata["updatetime"] = date("Y-m-d H:i:s");
						$imgdata["createUid"] = 0;
						$imgdata["types"] = 3;
						$imgdata["content"] = '万邑通美西仓发货成功,交易ID='.$rs_order['order_sn'].",运单号：".$vv['trackingNum'];
						$imgdata["createUser"] ='auto';
						$this->db->insert('db_goods_log', $imgdata);

						//更新另外一张表 方便日后报表统计
						$postdata="";
						$postdata["batch_order_sn"] = $rs_order["order_sn"];
						$postdata["batch_shipping_number"] = $vv['trackingNum'];
						$postdata["batch_shipping_name"] = $vv['deliverywayName'];
						$postdata["batch_orderweight"] = $rs_order['orderweight'];
						$postdata["oper"] = '沈龙';
						$postdata["opertime"] = date("Y-m-d H:i:s");
						$postdata["yz"] = 0;
						$postdata["skuNum"] = $sku_count;
						$postdata["skulist"] = ",".implode(",",$sku_list).",";
						$this->db->insert("db_order_batchexpress",$postdata);

						//更新库存信息 暂时临时库存表，不更新
						/**
						$sql_stock_uk = "SELECT * FROM db_order_sell a LEFT JOIN db_order_list b ON a.order_id = b.order_id WHERE a.salesOrderId = '".$vv["salerOrderId"]."'";
						$rs_stock_uk = $this->db->query($sql_stock_uk)->result_array();
						if(!empty($rs_stock_uk)){
							foreach($rs_stock_uk as $k=>$v){
								$this->db->set("stock = stock -",$v["goods_number"]);
								//$this->db->set('field', 'field+1');
								$this->db->where("goods_id",$v["goods_id"]);
								$this->db->update("db_goods_stock");
							}
						}**/
					}
				}
			}
		}
		//end
		echo "OK";exit;
	}
	//批量订单列表 在途数据更新每日 新系统订单编号20000开始
	//add 更新所有在途数 包括批量订单列表、以及质检处理中的待质检状态的订单
	public function updBatchOrderCount(){
		//每次执行 更新在途数量为0
		$upd_stock = "UPDATE db_goods_stock SET in_transit = 0 ,waitday=0";
		$this->db->query($upd_stock);
		//批量生产相关数量，日期导入

		//过滤工厂1 工厂2的添加人员
		$s = "SELECT GROUP_CONCAT(id) as id FROM d_user WHERE type = 1 AND (classid = 12 OR classid = 13 OR classid = 16) ";
		$r = $this->db->query($s)->row_array();

		$sql = "SELECT a.goods_id,a.goods_sku,GROUP_CONCAT(a.batchorder_id) as str_batchorder_id,sum(a.product_num) as totalcount,MAX(b.produce_date) AS produce_date,b.factory_goods_day,b.cang,b.goods_code FROM db_batchorder_list a LEFT JOIN db_batchorder b ON a.batchorder_id = b.order_id ".
			" WHERE b.status in(1,5,6) and b.userid not in({$r['id']}) and a.goods_id != 0 and a.goods_sku != '' and a.batchorder_id >20000 GROUP BY a.goods_id ORDER BY b.produce_date DESC ";
		$rs  = $this->db->query($sql)->result_array();
		foreach($rs as $key=>$value){
			$num     = $value['totalcount'];	//总数量
			//要减去相关扫件记录里面的数量
			$arr_batchorder_id = explode(",",$value['str_batchorder_id']);
			$arr_batchorder_id = array_flip($arr_batchorder_id);
			$arr_batchorder_id = array_flip($arr_batchorder_id);
			foreach($arr_batchorder_id as $k=>$v){
				if($value['goods_sku']){
					$sql_type = "SELECT * FROM db_batchorder_list WHERE goods_sku = '{$value['goods_sku']}' AND product_type != '' ";
					$rs_type  = $this->db->query($sql_type)->row_array();
					if(strlen($rs_type['product_type'])>5){
						$sql_scanorder = "SELECT sum(goods_num) as goods_num FROM db_factory_scanorder WHERE specifications = '{$rs_type['product_type']}' AND order_id = {$v}  ";
						$rs_scanorder  = $this->db->query($sql_scanorder)->row_array();
						if($rs_scanorder){
							$num = $num - $rs_scanorder['goods_num'];
							if($num<0){
								$num = 0;
							}
						}
					}
				}
			}

			if($value['cang']=='2号仓'){
				$sql_goods = "SELECT * FROM db_goods_stock WHERE goods_id = {$value['goods_id']} AND storage_id = 2 ";
				$rs_goods  = $this->db->query($sql_goods)->row_array();
				$cang = 2;
			}else{
				$sql_goods = "SELECT * FROM db_goods_stock WHERE goods_id = {$value['goods_id']} AND storage_id = 1 ";
				$rs_goods  = $this->db->query($sql_goods)->row_array();
				$cang = 1;
			}
			if($rs_goods){
				$upd = "UPDATE db_goods_stock SET in_transit = {$num},waitday = 0 WHERE storage_id = {$cang} AND id = {$rs_goods['id']} ";
				 $this->db->query($upd);
			}

		}
		echo "Batchorder SUCCESS";
		echo "<br/>";

		//质检处理里面相关商品sku在途数量统计
		$this->qualityCount($cang = 1,$supplierId =3); //一号仓
		$this->qualityCount($cang = 2,$supplierId = 3); //二号仓
		echo "Purchase SUCCESS";
		echo "<br/>";
		//exit;
		$this->qualityCount($cang = 1,$supplierId = 0); //一号仓
		$this->qualityCount($cang = 2,$supplierId = 0); //二号仓
		echo "other success";

	}
	//质检处理 相关在途数统计 $cang  仓位 1为一号仓  2为二号仓
	private function qualityCount($cang,$supplierId){
		//外采购 商品计算在途等
		if($supplierId==3){
			//ps = 2 付款完成
			$sql_purchaselist = "SELECT a.id,a.cang,a.tb_ordersn,b.order_id FROM db_purchase_list a ".
				"LEFT JOIN db_batchorder b ON a.tb_ordersn = b.order_id AND b.status != 3 ".
				"WHERE a.tb_ordersn != '' AND a.chkflag = 0 AND a.ps =2 AND made_factory='{$supplierId}'  AND a.cang = {$cang} GROUP BY a.id ";
			$rs_purchaselist = $this->db->query($sql_purchaselist)->result_array();

		}else{
			//获取 非 外采购  工厂1 工厂2 外的所有其他厂家id
			$sql_factory = "SELECT group_concat(id) as id FROM db_factory WHERE id not in(1,2,3) ";
			$rs_factory  = $this->db->query($sql_factory)->row_array();

			$sql_purchaselist = "SELECT a.id,a.cang,a.tb_ordersn,b.order_id FROM db_purchase_list a ".
				"LEFT JOIN db_batchorder b ON a.tb_ordersn = b.order_id AND b.status != 3 ".
				"WHERE a.tb_ordersn != '' AND a.chkflag = 0 AND made_factory in({$rs_factory['id']})  AND a.cang = {$cang} GROUP BY a.id ";
			$rs_purchaselist = $this->db->query($sql_purchaselist)->result_array();
		}

		$arr_purchase = array();
		foreach($rs_purchaselist as $k=>$v){
			if($v['order_id']){
				continue;
			}
			$arr_purchase[] = $v['id'];
		}
		if(count($arr_purchase)>0){
			$str_purchase = implode(",",$arr_purchase);
			//$sql_viceids = "SELECT GROUP_CONCAT(id) as str_viceids FROM db_purchase_vice WHERE pid in({$str_purchase}) ";
			//$rs_viceids  = $this->db->query($sql_viceids)->row_array();
			//$str_viceids = trim($rs_viceids['str_viceids'],",");

			// id pid 都是第一个条sku，符合计算在途等待天数的计算条件
			$sql_purchasevice = "SELECT id,pid,goods_id,good_no,sum(nums) as nums FROM db_purchase_vice WHERE pid in({$str_purchase}) GROUP BY goods_id,pid ";
			$rs_purchasevice  = $this->db->query($sql_purchasevice)->result_array();

			foreach($rs_purchasevice as $key=>$value){
				$arr_viceids[] = $value['id'];
			}
			$str_viceids = implode(",",$arr_viceids);

			foreach($rs_purchasevice as $kk=>$vv){
				$sql_vicelog = "SELECT goods_id,good_no,sum(inStockNum) as inStockNum FROM db_purchase_vicelog WHERE goods_id = '{$vv['goods_id']}' AND pid in({$str_viceids}) GROUP BY goods_id ";
				//$sql_vicelog = "SELECT goods_id,good_no,sum(inStockNum) as inStockNum FROM db_purchase_vicelog WHERE goods_id = '{$vv['goods_id']}' AND pid in({$str_viceids}) GROUP BY goods_id ";
				$rs_vicelog  = $this->db->query($sql_vicelog)->row_array();

				//计算在途等待天数
				$days = 0;
				if(count($rs_vicelog)>0){
					//可以直接使用该goods_id对应的在途天数
					//循环执行获取下一个goods_id的对应关系 计算在途天数
					$s_purchasevice = "SELECT * FROM db_purchase_vice WHERE goods_id = '{$vv['goods_id']}' AND pid in({$str_purchase}) ORDER BY id ASC  ";
					$r_purchasevice = $this->db->query($s_purchasevice)->result_array();
					foreach($r_purchasevice as $key=>$value){
						$s_vicelog = "SELECT sum(inStockNum) as inStockNum FROM db_purchase_vicelog WHERE pid = '{$value['id']}' AND goods_id = '{$value['goods_id']}' GROUP BY pid ";
						$r_vicelog = $this->db->query($s_vicelog)->row_array();
						if(count($r_vicelog)>0){
							if($value['nums']>$r_vicelog['inStockNum']){
								//直接计算在途天数
								$s_purchaselist = "SELECT * FROM db_purchase_list WHERE id = '{$value['pid']}' ";
								$r_purchaselist = $this->db->query($s_purchaselist)->row_array();
								$days = strtotime($r_purchaselist['opertime'])+$r_purchaselist['daysum']*86400;
							}else{

							}
						}else{
							//直接计算在途天数
							$s_purchaselist = "SELECT * FROM db_purchase_list WHERE id = '{$value['pid']}' ";
							$r_purchaselist = $this->db->query($s_purchaselist)->row_array();
							$days = strtotime($r_purchaselist['opertime'])+$r_purchaselist['daysum']*86400;
						}
					}
				}else{
					//直接计算在途天数
					$s_purchaselist = "SELECT * FROM db_purchase_list WHERE id = '{$vv['pid']}' ";
					$r_purchaselist = $this->db->query($s_purchaselist)->row_array();
					$days = strtotime($r_purchaselist['opertime'])+$r_purchaselist['daysum']*86400;
				}//在途天数计算结束
				if($days<0){
					$days = 0;
				}

				//在途数量
				$in_transit = 0;
				if(count($rs_vicelog)>0&&$rs_vicelog['inStockNum']){
					$in_transit = $vv['nums']- $rs_vicelog['inStockNum'];
				}else{
					$in_transit = $vv['nums'] ;
				}
				if($in_transit>0){
					$sql_goods_stock = "SELECT * FROM db_goods_stock WHERE goods_id = '{$vv['goods_id']}' AND storage_id = {$cang} ";
					$rs_goods_stock  = $this->db->query($sql_goods_stock)->row_array();
					if($rs_goods_stock){
						//更新
						$transit = $rs_goods_stock['in_transit']+$in_transit; //在途数量
						if($transit>0){
							$this->db->update('db_goods_stock',array('in_transit'=>$transit,'waitday'=>$days)," id = '".$rs_goods_stock['id']."'");

							if($rs_goods_stock['id'] ==22770){
								echo $this->db->last_query();
								echo "<br/>";
								echo $sql_goods_stock;
								echo "<br/>";
								print_r($vv);
								//echo $sql_vicelog;
								echo "<br/>";
								//print_r($rs_purchasevice) ;
								echo "<br/>";
								var_dump($rs_vicelog['inStockNum']);
							}
						}

					}else{
						//插入
						$arr_goods_stock = array();
						$arr_goods_stock['goods_id'] = $vv['goods_id'];
						if($cang == 1){
							$arr_goods_stock['storage_id'] = 1;
							$arr_goods_stock['storage_name'] = "一号仓";
						}
						if($cang == 2){
							$arr_goods_stock['storage_id'] = 2;
							$arr_goods_stock['storage_name'] = "二号仓";
						}
						$arr_goods_stock['stock'] = 0;
						$arr_goods_stock['in_transit'] = $in_transit;
						$arr_goods_stock['waitday'] = $days;
						$this->db->insert('db_goods_stock',$arr_goods_stock);

					}

				}
			}
		}


	}
	//每日统计 总库存数 以及 总库存价值
	public function getStockCountsPerDay(){
		$date_time = date("Y-m-d");
		$fields = "a.goods_id,a.storage_id,a.stock,b.g_supplier,b.g_sale_status,b.g_costprice,b.goods_sku ";
		$sql = "SELECT {$fields} FROM db_goods_stock a LEFT JOIN db_goods b ON a.goods_id = b.goods_id where a.storage_id !=8 and a.stock > 0";

		$rs  = $this->db->query($sql)->result_array();
		$data = array();
		$data["total_stock"] = 0;
		$data["total_value"] = 0;
		$data["normal_stock"] = 0;
		$data["normal_value"] = 0;
		$data["important_stock"] = 0;
		$data["important_value"] = 0;
		$data["stop_stock"] = 0;
		$data["stop_value"] = 0;
		$data["clear_stock"] = 0;
		$data["clear_value"] = 0;
		$data["one_stock"] = 0; //工厂1
		$data["one_value"] = 0;
		$data["two_stock"] = 0;//工厂2
		$data["two_value"] = 0;
		
		$data["one_cang"] = 0;//1号仓
		$data["one_cang_value"] = 0;
		$data["two_cang"] = 0;//2号仓
		$data["two_cang_value"] = 0;

		$data["de_cang"] = 0;//德国仓
		$data["de_cang_value"] = 0;
		$data["uk_cang"] = 0;//英国仓
		$data["uk_cang_value"] = 0;
		$data["usa_cang"] = 0;//美国仓
		$data["usa_cang_value"] = 0;
		$data["usax_cang"] = 0;//美西仓
		$data["usax_cang_value"] = 0;
		$data["fba_cang"] = 0;//FBA
		$data["fba_cang_value"] = 0;

		
		//德国仓，英国仓，美国仓，FBA仓,美西仓
		foreach($rs as $k=>$v){
			if($v["goods_sku"]){
				//获取成本
				$v['g_costprice'] = 0;
				if($this->CI->fun->getfactorygoodsku($v["goods_sku"]) == false)
				{
					$SKUcostprice  = $this->CI->fun->get_Goods_costprice($v["goods_sku"]);
					/**
					if($cangs["stock"]>0)
					{
						$stockPrice = $stockPrice+($cangs["stock"] * $SKUcostprice);
					}
					 * */
					$v['g_costprice'] = $SKUcostprice;

			

					$data["total_stock"] += $v['stock'];
					$data["total_value"] += $v['stock']*$v['g_costprice'];
					if($v['g_sale_status']==2){ //正常销售
						$data["normal_stock"] += $v['stock'];
						$data["normal_value"] += $v['stock']*$v['g_costprice'];
					}
					if($v['g_sale_status']==3){ //重点产品
						$data["important_stock"] += $v['stock'];
						$data["important_value"] += $v['stock']*$v['g_costprice'];
					}
					if($v['g_sale_status']==4){ //停产
						$data["stop_stock"] += $v['stock'];
						$data["stop_value"] += $v['stock']*$v['g_costprice'];
					}
					if($v['g_sale_status']==5){ //清仓
						$data["clear_stock"] += $v['stock'];
						$data["clear_value"] += $v['stock']*$v['g_costprice'];
					}
					if($v['g_supplier']==1){ //工厂1
						$data["one_stock"] += $v['stock'];
						$data["one_value"] += $v['stock']*$v['g_costprice'];
					}
					if($v['g_supplier']==2){ //工厂2
						$data["two_stock"] += $v['stock'];
						$data["two_value"] += $v['stock']*$v['g_costprice'];
					}

					if($v['storage_id']==1){ //1号仓
						$data["one_cang"] += $v['stock'];
						$data["one_cang_value"] += $v['stock']*$v['g_costprice'];
					}
					if($v['storage_id']==2){ //2号仓
						$data["two_cang"] += $v['stock'];
						$data["two_cang_value"] += $v['stock']*$v['g_costprice'];
					}
					if($v['storage_id']==5){ //德国仓
						$data["de_cang"] += $v['stock'];
						$data["de_cang_value"] += $v['stock']*$v['g_costprice'];
					}
					if($v['storage_id']==3){ //英国仓
						$data["uk_cang"] += $v['stock'];
						$data["uk_cang_value"] += $v['stock']*$v['g_costprice'];
					}
					if($v['storage_id']==6){ //英国仓
						$data["usa_cang"] += $v['stock'];
						$data["usa_cang_value"] += $v['stock']*$v['g_costprice'];
					}
					if($v['storage_id']==7){ //美西仓
						$data["usax_cang"] += $v['stock'];
						$data["usax_cang_value"] += $v['stock']*$v['g_costprice'];
					}
					if($v['storage_id']==9){ //FBA
						$data["fba_cang"] += $v['stock'];
						$data["fba_cang_value"] += $v['stock']*$v['g_costprice'];
					}
				}
			}
		}
		

		$data["total_value"] = number_format($data["total_value"],2);
		$data["normal_value"] = number_format($data["normal_value"],2);
		$data["important_value"] = number_format($data["important_value"],2);
		$data["stop_value"] =number_format($data["stop_value"],2);
		$data["clear_value"] = number_format($data["clear_value"],2);
		$data["one_value"] = number_format($data["one_value"],2);
		$data["two_value"] = number_format($data["two_value"],2);

		$data["one_cang_value"] = number_format($data["one_cang_value"],2);
		$data["two_cang_value"] =number_format($data["two_cang_value"],2);
		$data["de_cang_value"] = number_format($data["de_cang_value"],2);
		$data["uk_cang_value"] = number_format($data["uk_cang_value"],2);
		$data["usa_cang_value"] =number_format($data["usa_cang_value"],2);
		$data["usax_cang_value"] = number_format($data["usax_cang_value"],2);
		$data["fba_cang_value"] = number_format($data["fba_cang_value"],2);


		$data['addTime'] = $date_time;
		$sql_curdate = "SELECT * FROM db_goodstock_statistics WHERE addTime = '{$date_time}' ";
		$rs_curdate  = $this->db->query($sql_curdate)->row_array();
		if(count($rs_curdate)>0){
			$this->db->delete("db_goodstock_statistics"," addTime = '".$date_time."'");
		}
		$this->db->insert("db_goodstock_statistics",$data);
		echo "OK";exit;
	}
	//定期执行 计算正向开发提成
	public function Profit2newProduct(){
		$SQL = "SELECT * FROM db_product_develop WHERE status = 6 AND cutoff_time IS NULL AND overtime <= 1525017600";//截取到4月30号，5月新上的SKU，换另外的计算方式
		$list  = $this->db->query($SQL)->result_array();
		foreach($list as $key=>$rs)
		{
			$fields = "a.goods_id,a.goods_sn,a.goods_number,b.dates";
			$sql = "SELECT {$fields} FROM db_order_sell a LEFT JOIN db_order_list b ON a.order_id = b.order_id WHERE b.order_status in(4,5) AND b.order_source in('正常订单','手工创建','拆分订单','合并订单') AND  a.goods_sn in (SELECT goods_sku FROM db_goods WHERE goods_parent_sku = '{$rs['sku']}') ORDER BY b.dates ASC ";
			$result = $this->db->query($sql)->result_array();
			//亚马逊平台订单合并统计
			$amazon_fields = "a.goods_id,a.productid as goods_sn,a.ordernum as goods_number,b.dates";
			$sql_amazon = "SELECT {$amazon_fields} FROM db_amzordertmpsell a LEFT JOIN db_amzordertmp b ON a.ordertmpid = b.id WHERE a.productid in (SELECT goods_sku FROM db_goods WHERE goods_parent_sku = '{$rs['sku']}')  ORDER BY b.dates ASC ";
			$rs_amazon  = $this->db->query($sql_amazon)->result_array();
			$res = array();
			if(count($result)>0){
				if(count($rs_amazon)>0){
					if($result[0]['dates']>$rs_amazon[0]['dates']){
						$res = array_merge($rs_amazon,$result);
					}else{
						$res = array_merge($result,$rs_amazon);
					}
				}else{
					$res = $result;
				}
			}else{
				$res = $rs_amazon;
			}
			if(count($res)>0){
				$list['list'][$key]["startdate"] = $res[0]['dates'];
				$date_one = date("Y-m-d",(strtotime($res[0]['dates'])+30*86400)); //30天日期
				$date_two = date("Y-m-d",(strtotime($res[0]['dates'])+90*86400)); //90天日期
				$list['list'][$key]["enddate"] = date("Y-m-d",(strtotime($res[0]['dates'])+90*86400));

				if(!$rs['startdate']){
					$this->db->update("db_product_develop",array("startdate"=>$res[0]['dates'],"enddate"=>$list['list'][$key]["enddate"])," id = '".$rs['id']."'");
				}
				//if(!$rs['enddate']){
				//	$this->db->update("db_product_develop",array("enddate"=>$list['list'][$key]["enddate"])," id = '".$rs['id']."'");
				//}
				//$this->db->update("db_product_develop",array("startdate"=>$res[0]['dates'])," id = '".$rs['id']."'");
				//$this->db->update("db_product_develop",array("enddate"=>$list['list'][$key]["enddate"])," id = '".$rs['id']."'");
				//含连续30天计算

				$count_30day = 0; //30天内销量
				$count_90day = 0; //90天内销量
				$count_price = 0; //30天内提成
				$tmp_price = 0; //90天内提成
				//计算连续30天之内的销量
				$arr_30days = array();
				$arr_30days[] = array('begindate'=>$res[0]['dates'],'finishdate'=>$date_one);
				for($i=1;$i<=60;$i++){
					$begin_date = date("Y-m-d",(strtotime($res[0]['dates'])+$i*86400));
					$finish_date = date("Y-m-d",(strtotime($res[0]['dates'])+($i+30)*86400));
					$arr_30days[] = array('begindate'=>$begin_date,'finishdate'=>$finish_date);
				}
				$arr_order_sn = array();
				$arr_order_tradeid = array();
				foreach($arr_30days as $kk=>$vv){
					$compare_num  = 0;
					foreach($res as $ky=>$va){
						if(strtotime($va['dates'])>=strtotime($vv['begindate'])&&strtotime($va['dates'])<=strtotime($vv['finishdate'])){
								$compare_num+=$va['goods_number'];
								//$arr_order_sn[] = "'".$va['order_sn']."'";
								//$arr_order_tradeid[] = "'".$va['tradeid']."'";
						}
					}

					//计算30天内的退款信息
					if(count($arr_order_sn)>0){
						//$str_order_sn = implode(",",$arr_order_sn);
						//$str_order_tradeid = implode(",",$arr_order_tradeid);


						//获取所有退款信息
						/**
						$sql_refund = "select a.goods_number,a.goods_sn,c.order_sn from db_order_sell a left join db_order_list b on a.order_id = b.order_id ".
							"left join db_paypal_refund c on b.order_sn = c.order_sn where  c.order_sn in ($str_order_sn) ".
							" union ".
							"select a.goods_number,a.goods_sn,c.tradeid from db_order_sell a left join db_order_list b on a.order_id = b.order_id ".
							"left join db_amzordertmp_cancel c on b.tradeid = c.tradeid where  c.tradeid in($str_order_tradeid)".
							" union ".
							"select a.goods_number,a.goods_sn,c.order_number from db_order_sell a left join db_order_list b on a.order_id = b.order_id ".
							"left join db_wish_refund c on b.tradeid = c.tradeid where  c.tradeid in ($str_order_tradeid)";
						//$rs_refunds = $this->db->query($sql_refund)->result_array();


						if(count($rs_refunds)>0){
							foreach($rs_refund as $ky=>$val){
								$compare_num = $compare_num-$val['goods_number'];
							}
						}**/
					}
					if($compare_num>$count_30day){
						$count_30day = $compare_num;
					}
				}
				foreach($res as $k=>$v){
					//计算连续满30天的销量，同时扣除该连续30天之内的相关退款数量
					/**
					if($v['dates']<=$date_one){
					$count_30day += $v['goods_number'];
					}**/
					//90天之内的销量
					if(strtotime($v['dates'])<=strtotime($date_two)){
						$count_90day += $v['goods_number'];
					}
				}
				/**
				if(!$rs['startdate']){
					$this->db->update("db_product_develop",array("startdate"=>$res[0]['dates'])," id = '".$rs['id']."'");
				}
				if(!$rs['enddate']){
					$this->db->update("db_product_develop",array("enddate"=>$list['list'][$key]["enddate"])," id = '".$rs['id']."'");
				}
				$count_30day = 0; //30天内销量
				$count_90day = 0; //90天内销量
				$count_price = 0;
				$tmp_price = 0;
				foreach($res as $k=>$v){
					if($v['dates']<=$date_one){
						$count_30day += $v['goods_number'];
					}
					if($v['dates']<=$date_two){
						$count_90day += $v['goods_number'];
					}
				}**/
				if($count_30day>=10){
					$count_price = 300;
				}
				if($count_30day>=20){
					$count_price = 600;
				}
				if($count_30day>=30){
					$count_price = 900;
				}
				//90天
				if($count_90day>=30){
					$tmp_price = 300;
				}
				if($count_90day>=60){
					$tmp_price = 600;
				}
				if($count_90day>=90){
					$tmp_price = 900;
				}
				if($tmp_price>$count_price){   //获取最大提成金额
					$count_price = $tmp_price;
				}

				$list['list'][$key]["count_30day"] = $count_30day;
				$list['list'][$key]["count_90day"] = $count_90day;
				$list['list'][$key]["count_price"] = $count_price;
				if(!$rs['cutoff_time']){
					$this->db->update("db_product_develop",array("cutoff_money"=>$count_price,"nums_30day"=>$count_30day,"nums_90day"=>$count_90day)," id = '".$rs['id']."'");
				}
			}

		}
		echo "OK";exit;
	}
	//每天提醒销售，相应订单亏本情况
	public function sendMessageToSales(){
		//当前时间 前五天
		$cur_time = time()-2*86400;
		$cur_datetime = date("Y-m-d H:i:s",$cur_time);
		//循环销售
		//$sql = "SELECT * FROM d_user WHERE type = 1 AND id = 295 ";
		$sql = "SELECT id,name FROM d_user WHERE type = 1 AND classid in(2,3,4,5,6) ";
		$rs  = $this->db->query($sql)->result_array();
		if(count($rs)>0){
			foreach($rs as $k_user=>$v_user){
				$arr_order_count = array();
				//订单状态 2,3 已支付 以配货  正常订单
				$sql_order = "SELECT order_id,shipping_realfee,shipping_expectfee,goods_amount,shipping_fee,platform_fee,pay_fee,order_sn FROM db_order_list WHERE shopoper = '{$v_user['name']}' AND order_status in(2,3) AND order_source = '正常订单' AND dates >= '{$cur_datetime}' ";
				$rs_order  = $this->db->query($sql_order)->result_array();
				if(count($rs_order)>0){
					foreach($rs_order as $k_order=>$v_order){
						$sql_goodslist = "SELECT goods_number,costprice,goods_sn FROM db_order_sell a LEFT JOIN db_goods b ON a.goods_sn = b.goods_sku WHERE a.order_id = '{$v_order['order_id']}' ";
						$rs_goodslist  = $this->db->query($sql_goodslist)->result_array();
						$allcostprice = 0;
						if(count($rs_goodslist)>0){
							foreach($rs_goodslist as $k_goods=>$v_goods){
								//$costprice = $v_goods["costprice"];
								$costprice = $this->CI->fun->get_Goods_costprice($v_goods['goods_sn']);
								$acostprice = $costprice * $v_goods["goods_number"];
								$allcostprice = $allcostprice + $acostprice;
							}
						}
						if($v_order["shipping_realfee"]>0)
							$shippingfee = $v_order["shipping_realfee"];
						else
							$shippingfee = $v_order["shipping_expectfee"];
						$profit = 0;
						$profit = $v_order["goods_amount"] + $v_order["shipping_fee"] - $allcostprice - $shippingfee - $v_order["platform_fee"] - $v_order["pay_fee"];
						$profit = round($profit,2);
						//$profit = $profit -100; //测试
						if($profit<0){
							$arr_order_count[] = $v_order['order_sn'];
						}
					}
				}
				//若符合条件，对相关用户发送提醒消息
				if(count($arr_order_count)>0){
					//设置系统Message提醒
							$randid = $this->CI->message->getMessageNums();	//获取当前存储的条数
							$postData = "";
							$postData["message_type"] = "【订单负利润】";	
							$message = "当前系统共有 ".count($arr_order_count)." 个订单负利润。请知晓！<br>";
							 foreach($arr_order_count as $kk=>$vv){
						      //  $message.= "<a href=/orderlist/editorder?sn={$v_order[order_sn]} target=_thank>".$vv."</a><br/>";
							    $message.= $vv."<br>";
					        }
							$postData["message"] = $message;
							$postData["message_toName"] =$v_user['name'];
							$postData["isread"] =  $randid;
							$postData["url"] = '/orderlist/orderlist';
							$postData["message_toID"] =  $v_user["id"];	//接收对象ID
							$postData["message_formID"] = 0;
							$postData["message_formName"] = 'SYSYTEM';
							$this->CI->message->saveMessage($postData);
				}
			}
		}
	}
	//销售达指定数量的商品提醒设置相关子sku信息 发送信息给刘艺 李明道
	public function sendMessageBySalesCount(){
		$count = trim($this->CI->config->item("salesgoodscount")); //销售商品的数量
		$sql = "SELECT * FROM db_factory_salereport WHERE num2 >= '{$count}' AND sku_exists = 0 AND model in(1,2) ";
		$rs  = $this->db->query($sql)->result_array();
		if(count($rs)>0){
			$arr_asia = array(); //亚洲
			$arr_us   = array(); //欧美
			foreach($rs as $k_sales=>$v_sales){
				//判断商品相关型号
				$size = $v_sales['size'];
				if($v_sales['model']==1){
					$model = "欧美";
				}
				if($v_sales['model']==2){
					$model = "亚洲";
				}
				if($v_sales['gender']==1){
					$gender = "男性";
				}
				if($v_sales['gender']==2){
					$gender = "女性";
				}
				$sql_goods = "SELECT goods_id FROM db_goods WHERE goods_parent_sku = '{$v_sales['goos_sku']}' AND goods_sku != '{$v_sales['goos_sku']}' ";
				$rs_goods  = $this->db->query($sql_goods)->result_array();
				if(count($rs_goods)>0){
					$exist_flag = 0;
					foreach($rs_goods as $k_goods=>$v_goods){
							$sql_attr = "SELECT GROUP_CONCAT(attr_value) as attr_value FROM db_goods_attr WHERE goods_id = '{$v_goods['goods_id']}' order by attr_id asc ";
						    $rs_attr  = $this->db->query($sql_attr)->row_array();
							// $rs_attr 女性,M,亚洲
							if($rs_attr){
								$arr_attr = explode(",",$rs_attr['attr_value']);
								/**
								if($v_sales['goos_sku']=="12001461"){
									print_r($arr_attr);exit;
								}**/

								if(in_array($size,$arr_attr)&&in_array($model,$arr_attr)&&in_array($gender,$arr_attr)){
									//更新 说明已经添加过相关子sku
									$exist_flag = 1;
									$this->db->update("db_factory_salereport",array("sku_exists"=>1)," id = '".$v_sales['id']."'");
									break;
								}
							}
					}
					//若不存在
					if($exist_flag==0){
						if($v_sales['model']==1){
							$arr_us[] = $v_sales['goos_sku']; //欧美
						}
						if($v_sales['model']==2){
							$arr_asia[] = $v_sales['goos_sku']; //亚洲
						}
					}
				}else{
					if($v_sales['model']==1){
						$arr_us[] = $v_sales['goos_sku']; //欧美
					}
					if($v_sales['model']==2){
						$arr_asia[] = $v_sales['goos_sku']; //亚洲
					}
				}
			}
			//判断欧美 亚洲是否存在相关未录入子SKU信息

			//设置系统Message提醒
			$randid = $this->CI->message->getMessageNums();	//获取当前存储的条数
			$postData = "";
			$postData["message_type"] = "【消息提醒】";
			$message = "工厂商品销量有大于".$count."件的商品未录入相关子SKU";
			$postData["message"] = $message;
			$postData["isread"] =  $randid;
			$postData["message_formID"] = 0;
			$postData["message_formName"] = 'SYSYTEM';
			if(count($arr_asia)>0){
				$postData["url"] = '/goodsreport/showreport?model=2&sku_exists=0&d=2&sales='.$count;
				$postData["message_toName"] ="李明道";
				$postData["message_toID"] =  79;	//接收对象ID 79 李明道
				$this->CI->message->saveMessage($postData);
			}
			if(count($arr_us)>0){
				$postData["url"] = '/goodsreport/showreport?model=1&sku_exists=0&d=2&sales='.$count;
				$postData["message_toName"] ="刘艺";
				$postData["message_toID"] =  120;	//接收对象ID 120 刘艺
				$this->CI->message->saveMessage($postData);
			}


		}
		echo "OK";exit;
	}
	//获取外采购商品库息
	public function getStockInterestPerDay(){
		//获取所有需要统计信息的外采购商品  5.4 清仓商品  下架商品
		$time = time();


		$sql_buy = "SELECT a.id,a.stockInterest,a.sku,GROUP_CONCAT(c.goods_sku) as str_goods_sku,GROUP_CONCAT(c.goods_id) as str_goods_id FROM db_external_buy a ".
					"LEFT JOIN db_goods_parent b ON a.sku = b.p_parent_sku ".
					"LEFT JOIN db_goods c ON b.p_parent_sku = c.goods_parent_sku ".
					"WHERE a.status = 99 AND c.g_sale_status not in(5) GROUP BY a.id ";
		$rs_buy = $this->db->query($sql_buy)->result_array();
		
		if(count($rs_buy)>0){
			foreach($rs_buy as $k_buy=>$v_buy){
				//$sku = $v_buy['sku'];
				//$arr_sub_sku = explode(",",$v_buy['str_goods_sku']);
				//$arr_goods_id= explode(",",$v_buy['str_goods_id']);
				$sql_stock = "SELECT goods_id,sum(stock) as stock FROM db_goods_stock WHERE storage_id in(1,2) AND  goods_id in({$v_buy['str_goods_id']}) GROUP BY goods_id HAVING sum(stock)>0 ";
				$rs_stock  = $this->db->query($sql_stock)->result_array();
				if(count($rs_stock)>0){
					$stock_money = 0;
					foreach($rs_stock as $k_stock=>$v_stock){
						if($v_stock['stock']>0){
							//增加库存日志 type 1为增加库存 0为减少库存
							$sql_stocklog_add = "SELECT goods_id,updatetime,stock FROM db_goods_stock_log WHERE type = 1 AND goods_id = '{$v_stock['goods_id']}' ORDER BY id ASC ";
							$rs_stocklog_add  = $this->db->query($sql_stocklog_add)->result_array();
							if(!$rs_stocklog_add){
								continue; //如日志不存在则不计算
							}
							//扣减的库存
							$sql_stocklog_reduce = "SELECT sum(abs(stock)) as stock FROM db_goods_stock_log WHERE type = 0 AND goods_id = '{$v_stock['goods_id']}' and updatetime >='".$rs_stocklog_add[0]['updatetime']."' "; //只计算记录到的最小时间
							$rs_stocklog_reduce  = $this->db->query($sql_stocklog_reduce)->row_array();
							$out_stock = !empty($rs_stocklog_reduce['stock'])?$rs_stocklog_reduce['stock']:0;
							$in_stock = 0;
						
							foreach($rs_stocklog_add as $k_stocklog=>$v_stocklog){
								
								$in_stock_time = strtotime($v_stocklog['updatetime']);
								$count_days = round(($time-$in_stock_time)/86400,2);
								$in_stock = $in_stock+$v_stocklog['stock'];
								
								$num  = $in_stock - $out_stock;
								
								if($num>0){

									//计算库息
									$sql_goods = "SELECT goods_sku FROM db_goods WHERE goods_id = '{$v_stocklog['goods_id']}' ";
									$rs_goods = $this->db->query($sql_goods)->row_array();
									$costprice = $this->CI->fun->get_Goods_costprice($rs_goods['goods_sku']);

									if($count_days<30){
										continue; //不计算库息
									}
									if($count_days>30&&$count_days<90){
										//按库存金额（库存数*SKU成本（关联，成本））的千分之一 / 日 计算库息
										//$cur_stock = $all_stock_num - $out_stock; //备注 此处可以使用实际库存数？
										$cur_stock = $num;//当前还剩余库存
										$money = ($cur_stock * $costprice) * 0.001;
										$stock_money = $money+$stock_money;
									}
									if($count_days>90){
										//$cur_stock = $all_stock_num - $out_stock;
										$cur_stock = $num;
										$allmoney = $cur_stock * $costprice;
										$money = ($cur_stock * $costprice) * 0.003;
										$stock_money = $money+$stock_money;
									}
									//print_r($stock_money);exit;
								}

							}
						}
					}//foreach $rs_stock end
					$stock_money = round($stock_money,2);
					if($stock_money>0){
						$all_money = $stock_money+$v_buy['stockInterest'];
						$this->db->update("db_external_buy",array("stockInterest"=>$all_money)," id = '".$v_buy['id']."'");
					}
				}
			} // foreach rs_buy end
		}
		echo "OK";
	}

	/*******FBA按店铺存库息***********/
	public function getStockInterestPerDayFBA(){
		$time = time();
		/*
		$Data = $this->CI->fun->getdatabaseslist('db_goods_stock_log A left join db_goods B on A.goods_id = B.goods_id ',"  AND `isfba` = 1 "," A.goods_id ,A.shopid,B.goods_sku");
		$insert_batck=0;
		foreach($Data as $key=>$rs)
		{
			$post = "";
			$rsdb = $this->CI->fun->getdatabasesdetail('db_goods_stock_interest'," AND goods_id='".$rs["goods_id"]."' AND shopid ='".$rs["shopid"]."' ");
			if(!$rsdb)
			{
				$post["goods_id"] = $rs["goods_id"];
				$post["goods_sku"] = $rs["goods_sku"];
				$post['isfba']    = 1;
				$post['shopid']   = $rs["shopid"];
				$post['starttime'] = time();
				$post['settlement'] = 0;
				$post['interest'] = 0;
				$post['interest_allnum'] =0;
				$this->db->insert('db_goods_stock_interest',$post);
			}
		}*/
		
		$Data = $this->CI->fun->getdatabaseslist('db_fba_stock  ',"  AND goods_id >0 "," goods_id ,shopid,sku");
		foreach($Data as $key=>$rs)
		{
			$post = "";
			$rsdb = $this->CI->fun->getdatabasesdetail('db_goods_stock_interest'," AND goods_id='".$rs["goods_id"]."' AND shopid ='".$rs["shopid"]."' ");
			if(!$rsdb)
			{
				$post["goods_id"] = $rs["goods_id"];
				$post["goods_sku"] = $rs["sku"];
				$post['isfba']    = 1;
				$post['shopid']   = $rs["shopid"];
				$post['starttime'] = time();
				$post['settlement'] = 0;
				$post['interest'] = 0;
				$post['interest_allnum'] =0;
				$this->db->insert('db_goods_stock_interest',$post);
			}
		}
	
		//开始计算库息
		
		$rs_buy = $this->CI->fun->getdatabaseslist('db_goods_stock_interest ',"  AND `isfba` = 1  ","goods_id,shopid,goods_sku,interest,id");
		foreach($rs_buy as $k_buy=>$v_buy){
			$stock_money = 0;
			$rs_stock  = $this->CI->fun->getdatabasesdetail('db_fba_stock'," AND  goods_id = '".$v_buy['goods_id']."' and Warehouse_code = 'SELLABLE' and shopid = '".$v_buy['shopid']."'","goods_id,Quantity");
			if($rs_stock['Quantity']>0){
						//增加库存日志 type 1为增加库存 0为减少库存
						$sql_stocklog_add = "SELECT goods_id,fulflllment_data as updatetime, quantity as stock FROM db_fba_fulflllment WHERE goods_id = '{$rs_stock['goods_id']}' and shopid = '".$v_buy['shopid']."' AND fulflllment_data >='2018-04-01' ORDER BY fulflllment_data ASC ";
						$rs_stocklog_add  = $this->db->query($sql_stocklog_add)->result_array();
						if(!$rs_stocklog_add){
							continue; //如日志不存在则不计算
						}
						
						//扣减的库存
						$sql_stocklog_reduce = "SELECT sum(abs(stock)) as stock FROM db_goods_stock_log WHERE type = 0 AND isfba = 1 AND goods_id = '{$rs_stock['goods_id']}'  and shopid = '".$v_buy['shopid']."' and updatetime >='".$rs_stocklog_add[0]['updatetime']."'  "; //只计算记录到的最小时间
						$rs_stocklog_reduce  = $this->db->query($sql_stocklog_reduce)->row_array();
						$out_stock = !empty($rs_stocklog_reduce['stock'])?$rs_stocklog_reduce['stock']:0;
						$in_stock = 0;

						
						foreach($rs_stocklog_add as $k_stocklog=>$v_stocklog){
							
							$in_stock_time = strtotime($v_stocklog['updatetime']);
							$count_days = round(($time-$in_stock_time)/86400,2);
							$in_stock = $in_stock+$v_stocklog['stock'];
							$num  = $in_stock - $out_stock;
						
							if($num>0){

								//计算库息
								$costprice = $this->CI->fun->get_Goods_costprice($v_buy['goods_sku']);
								/*
								if($count_days<15){
									continue; //垫资时间小于15天  不计算任何库存利息
								}
								if($count_days>15&&$count_days<30){	//垫资时间在15至30天,结算时按照日万分之五来计库存成本
									
									$cur_stock = $num;//当前还剩余库存
									$money = ($cur_stock * $costprice) * 0.0005;
									$stock_money = $money+$stock_money;
								}
								if($count_days>30&&$count_days<60){	//垫资时间30至60天  按照所垫资金的千分之一/日计算库存利息；
									
									$cur_stock = $num;//当前还剩余库存
									$money = ($cur_stock * $costprice) * 0.001;
									$stock_money = $money+$stock_money;
								}
								*/
								if($count_days>=60){
									//$cur_stock = $all_stock_num - $out_stock;
									$cur_stock = $num;
									$allmoney = $cur_stock * $costprice;
									$money = ($cur_stock * $costprice) * 0.003;
									$stock_money = $money+$stock_money;
								}
								
								
								//print_r($stock_money);exit;
							}
							//echo "<br>";
							//echo $in_stock."->".$num."->".$count_days."->".$v_stocklog['updatetime']."->".$stock_money."->".$costprice;
							//echo "<br>";
						}
					
				$stock_money = round($stock_money,2);
			
				if($stock_money>0){
					$all_money = $stock_money+$v_buy['interest'];
					$this->db->update("db_goods_stock_interest",array("interest"=>$all_money)," id = '".$v_buy['id']."'");
				}
			}
		}
		
		return true;
	}

	//将商品销售日均达一定数量的商品自动标为重要商品
	public function setImportantGoods(){
		// 2 正常销售  3 重要商品
		$sql = "SELECT goods_id,dailysales,g_sale_status FROM db_goods WHERE g_sale_status = 2 or g_sale_status = 6 ";
		$rs  = $this->db->query($sql)->result_array();
		$arr_normal_sale = array();
		$arr_important_sale = array();
		foreach($rs as $key=>$value){
			if($value['g_sale_status']==2&&$value['dailysales']>1){
				$arr_important_sale[] = $value['goods_id'];
			}
			if($value['g_sale_status']==6&&$value['dailysales']<1){
				$arr_normal_sale[] = $value['goods_id'];
			}

		}
		if(count($arr_normal_sale)>0){
			$str_normal_sale = implode(",",$arr_normal_sale);
			$this->db->update("db_goods",array("g_sale_status"=>2)," goods_id in (".$str_normal_sale.")");

		}
		if(count($arr_important_sale)>0){
			$str_important_sale = implode(",",$arr_important_sale);
			$this->db->update("db_goods",array("g_sale_status"=>6)," goods_id in (".$str_important_sale.")");
		}
		echo "OK";exit;

	}
	//模拟post请求
	public function sendCurlPostRequest($url,$post_data,$headers){
		$ch = curl_init($url);
		curl_setopt($ch,CURLOPT_URL,$url);
		curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
		curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
		curl_setopt($ch,CURLOPT_POST,1);
		curl_setopt($ch,CURLOPT_POSTFIELDS,$post_data);
		// https请求 不验证证书和hosts
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
		$output = curl_exec($ch);
		//print_r($output);exit;
		curl_close($ch);
		$output= json_decode($output,1);
		return $output;
	}
	//模拟get请求
	public function sendCurlGetRequest($url,$token){
		$headers = array("Authorization: Bearer {$token}");
		$ch = curl_init($url);
		curl_setopt($ch,CURLOPT_URL,$url);
		curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
		curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
		// https请求 不验证证书和hosts
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
		$output = curl_exec($ch);
		curl_close($ch);
		$output= json_decode($output,1);
		return $output;

	}
	//模拟CURL请求
	public function sendCurlCommonRequest($url,$method="post",$post_data,$headers){
		$ch = curl_init();
		curl_setopt($ch,CURLOPT_URL,$url);
		if(count($headers)>0){
			curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
		}
		curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
		$method = strtoupper($method);
		switch ($method){
			case "GET":
				//curl_setopt($ch, CURLOPT_HTTPGET, true);
				break;
			case "POST":
				curl_setopt($ch,CURLOPT_POST,1);
				curl_setopt($ch,CURLOPT_POSTFIELDS,$post_data);
			case "PUT":
				curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, "PUT");
				curl_setopt($ch, CURLOPT_POSTFIELDS,$post_data);
				break;
			case "DELETE":
				curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
				//curl_setopt($ch, CURLOPT_POSTFIELDS,$post_data);
				break;
		}
		// https请求 不验证证书和hosts
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
		$output = curl_exec($ch);
		$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
		//var_dump($output);exit;
		curl_close($ch);

		return $httpCode;
		//return $output;
	}
}